echo 是一個 Shell 内建指令,用來在終端輸出字元串,并在最後預設加上換行符。請看下面的例子:
#!/bin/bash
name="Shell教程"
url="http://c.biancheng.net/shell/"
echo "讀者,你好!" #直接輸出字元串
echo $url #輸出變量
echo "${name}的網址是:${url}" #雙引号包圍的字元串中可以解析變量
echo '${name}的網址是:${url}' #單引号包圍的字元串中不能解析變量
運作結果:
讀者,你好!
http://c.biancheng.net/shell/
Shell教程的網址是:http://c.biancheng.net/shell/
${name}的網址是:${url}
不換行
echo 指令輸出結束後預設會換行,如果不希望換行,可以加上-n參數,如下所示:
#!/bin/bash
name="Tom"
age=20
height=175
weight=62
echo -n "${name} is ${age} years old, "
echo -n "${height}cm in height "
echo "and ${weight}kg in weight."
echo "Thank you!"
運作結果:
Tom is 20 years old, 175cm in height and 62kg in weight.
Thank you!
輸出轉義字元
預設情況下,echo 不會解析以反斜杠\開頭的轉義字元。比如,\n表示換行,echo 預設會将它作為普通字元對待。請看下面的例子:
[[email protected] ~]# echo "hello \nworld"
hello \nworld
我們可以添加-e參數來讓 echo 指令解析轉義字元。例如:
[[email protected] ~]# echo -e "hello \nworld"
hello
world
\c 轉義字元
有了-e參數,我們也可以使用轉義字元\c來強制 echo 指令不換行了。請看下面的例子:
#!/bin/bash
name="Tom"
age=20
height=175
weight=62
echo -e "${name} is ${age} years old, \c"
echo -e "${height}cm in height \c"
echo "and ${weight}kg in weight."
echo "Thank you!"
運作結果:
Tom is 20 years old, 175cm in height and 62kg in weight.
Thank you!