- Mastering Linux Shell Scripting
- Andrew Mallett
- 282字
- 2021-07-30 09:40:46
Enhancing scripts with read prompts
We have seen how we can use the built in read to populate a variable. So far, we have used echo
to produce the prompt but this can be passed to read itself using the -p
option. The read
command will surpass the additional linefeed, so we reduce both the line count and the complexity to some degree.
We can test this at the command line itself. Try typing the following command to see read
in action:
$ read -p "Enter your name: " name
We use the read
command with the -p
option. The argument that follows the option is the text that appears in the prompt. Normally, we will make sure that there is a trailing space at the end of the text to ensure that we can clearly see what we type. The last argument supplied here is the variable we want to populate, we simply call it name
. Variables are case-sensitive too. Even if we did not supply the last argument, we can still store the user's response, but this time in the REPLY
variable.
Tip
Note that when we return the value of a variable we use $
but not when we write it. In simple terms when reading a variable we refer to $VAR
when setting a variable we refer to VAR=value
.
The following illustration shows the read
command with syntax using the -p
option:

We can edit the script so that it appears similar to the following extract from hello3.sh
:
#!/bin/bash read -p "May I ask your name: " name echo "Hello $name" exit 0
The read
prompt cannot evaluate commands within the message string, such as we used before.
- Mastering Ext JS(Second Edition)
- 深度實踐OpenStack:基于Python的OpenStack組件開發
- Interactive Data Visualization with Python
- Vue.js快跑:構建觸手可及的高性能Web應用
- C#程序設計(慕課版)
- Mastering Julia
- Elasticsearch Server(Third Edition)
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- Web性能實戰
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- 計算機應用基礎教程(Windows 7+Office 2010)
- Orchestrating Docker
- Node.js區塊鏈開發
- Arduino機器人系統設計及開發
- H5匠人手冊:霸屏H5實戰解密