Latest web development tutorials

Shell echo命令

Shell 的echo 指令與PHP 的echo 指令類似,都是用於字符串的輸出。 命令格式:

echo string

您可以使用echo實現更複雜的輸出格式控制。

1.顯示普通字符串:

echo "It is a test"

這裡的雙引號完全可以省略,以下命令與上面實例效果一致:

echo It is a test

2.顯示轉義字符

echo "\"It is a test\""

結果將是:

"It is a test"

同樣,雙引號也可以省略

3.顯示變量

read 命令從標準輸入中讀取一行,並把輸入行的每個字段的值指定給shell 變量

#!/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.顯示換行

echo -e "OK! \n" # -e 开启转义
echo "It it a test"

輸出結果:

OK!

It it a test

5.顯示不換行

#!/bin/sh
echo -e "OK! \c" # -e 开启转义 \c 不换行
echo "It is a test"

輸出結果:

OK! It is a test

6.顯示結果定向至文件

echo "It is a test" > myfile

7.原樣輸出字符串,不進行轉義或取變量(用單引號)

echo '$name\"'

輸出結果:

$name\"

8.顯示命令執行結果

  echo `date`

結果將顯示當前日期

Thu Jul 24 10:08:46 CST 2014