Shell echo命令:輸出字符串
echo 是一個 Shell 內建命令,用來在終端輸出字符串,並在最后默認加上換行符。請看下面的例子:
#!bin/bash name="tom" age=26 height=175 weight=65 echo "你好!" #直接輸出字符串 echo $name #輸出變量 echo "${name}的年齡是${age},身高為:${height},體重為:${weight}kg。" #雙引號包圍的字符串中可以解析變量 echo '${name}的年齡是${age},身高為:${height},體重為:${weight}kg。' #單引號包圍的字符串中不能解析變量
運行結果:
你好! tom tom的年齡是26,身高為:175,體重為:65kg。 ${name}的年齡是${age},身高為:${height},體重為:${weight}kg。
不換行
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 默認會將它作為普通字符對待。請看下面的例子:
[root@localhost ~]# echo "hello \nworld" hello \nworld
我們可以添加-e參數來讓 echo 命令解析轉義字符。例如:
[root@localhost ~]# 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!
