官术网_书友最值得收藏!

Limiting the number of entered characters

We do not need functionality in the scripts we have used so far, but we may need to ask users to hit any key to continue. At the moment, we have set it up in such a way that the variable is not populated until we hit the Enter key. Users have to hit Enter to continue. If we use the -n option followed by an integer, we can specify the characters to accept before continuing, we will set 1 in this case. Take a look at the following code extract:

#!/bin/bash
read -p "May I ask your name: " name
echo "Hello $name"
read -n1 -p "Press any key to exit"
echo
exit 0

Now, the script will pause after displaying the name until we press any key; literally, we can press any key before continuing, as we accept just 1 key stroke. Whereas, earlier we were required to leave the default behavior in place, as we could not know how long a entered name would be. We have to wait for the user to hit Enter.

Tip

Note that we add an additional echo here to ensure that a new line is issued before the script ends. This ensures that the shell prompt starts on a new line.

主站蜘蛛池模板: 海盐县| 基隆市| 樟树市| 和静县| 从化市| 永泰县| 五家渠市| 荥经县| 宜阳县| 正镶白旗| 昌平区| 红桥区| 长丰县| 林州市| 哈巴河县| 双城市| 松潘县| 富平县| 鄂伦春自治旗| 灵丘县| 石台县| 洞口县| 当阳市| 来凤县| 托克托县| 白山市| 荣昌县| 吴堡县| 永善县| 天全县| 兴业县| 沙洋县| 遂平县| 阜宁县| 兴安盟| 曲麻莱县| 威远县| 九江市| 普陀区| 蕉岭县| 澎湖县|