Shell echo command
Shell's echo command is similar to PHP's echo command, both of which are used for string output . Command format: echo string
You can use echo for more sophisticated output format control.
1. Display a normal string: echo "It is a test" , the double quotes here can be completely omitted,
The following command has the same effect as the above example: echo It is a test
2. Display escape characters : echo "\"It is a test\"" , the result will be: "It is a test" , also, double quotes can be omitted.
Remarks: \" \": Transfer a pair of "" symbols.
3. Display variables: The read command reads a line from standard input and assigns the value of each field of the input line to a shell variable
#!/bin/sh
read name
echo "$name It is a test"
以上代码保存为 test.sh,name 接收标准输入的变量,结果将是:
[root@www ~]# sh test.sh
OK #标准输入
OK It is a test #输出
4. Display newline: Note: echo -e
echo -e "OK! \n" # -e 开启转义
echo "It it a test"
输出结果:
OK!
-- 备注:(有一空行)
It it a test
5. Display does not wrap: Note: echo -e
#!/bin/sh
echo -e "OK! \c" # -e 开启转义 \c 不换行
echo "It is a test"
输出结果:
OK! It is a test
6. The display result is directed to the file: echo "It is a test" > myfile; (the first contact with this operation)
7. Output the string as it is, without escaping or taking variables (with single quotes):
echo '$name\"'
输出结果:
$name\"
8. Display the command execution result:
echo `date`
注意: 这里使用的是反引号 `, 而不是单引号 '。
结果将显示当前日期
2018年 3月11日 星期日 11时57分18秒 CST
Remark 1: String summary of echo output:
===================================================== ================
Can reference variables | Can reference transfer characters | Can reference text format characters (such as line breaks, tabs)
single quote | no | no | no
double quotes | can | can | can
no quotes | can | can | no
=========================================== ===========================
Remarks 2. The read command is related:
The read command receives the input parameters one by one, and each phrase needs to be separated by a space; if the number of input phrases is greater than the required number of parameters, the extra phrases will be received as the last parameter as a whole.
The test file test.sh code is as follows:
read firstStr secondStr
echo "第一个参数:$firstStr; 第二个参数:$secondStr"
执行测试:
$ sh test.sh
一 二 三 四
第一个参数:一; 第二个参数:二 三 四
Example, file test.sh:
read -p "请输入一段文字:" -n 6 -t 5 -s password
echo "\npassword is $password"
Parameter Description:
- -p enter prompt text
- -n input character length limit (up to 6 digits, automatic end)
- -t input time limit
- -s hide input
$ sh test.sh
请输入一段文字:
password is asdfgh