1. echo 命令
echo 是基本的shell輸出命令,她的語法是:
echo string
我們也可以使用她來定制一些輸出的格式,具體如下:
輸出普通字符串
echo "it is a echo string here!"
PS: 引號可以省略。
顯示變量
read 命令從標准輸入中讀取一行,並把輸入行的每個字段的值指定給 shell 變量
#!/bin/sh read name echo "$name It is a test"
以上代碼保存為 test.sh,name 接收標准輸入的變量,結果將是:
# sh test.sh OK #標准輸入 OK It is a test #輸出
開啟轉義
echo -e string
示例:
#!/bin/sh echo -e "OK! \n" # -e 開啟轉義 echo "It it a test" 結果為: OK! It it a test --- echo -e "OK! \c" # -e 開啟轉義 \c 不換行 echo "It is a test" 結果為: OK! It is a test
結果定向至文件
echo "output to a file" > myfile
原樣輸出 (使用單引號括起來)
#!/bin/bash echo '$name\ "" '
輸出命令執行結果 (使用``括起來)
#!/bin/bash echo `date` 輸出為: Wed Mar 1 03:40:19 UTC 2017
--我是分割線--
2. printf 命令
類似C語言的printf函數,語法為:
printf format-string [arguments...]
參數說明:
- format-string: 為格式控制字符串,例如 %s %c %d %f都是格式替代符
- arguments: 為參數列表。
示例:
!bin/bash # "%d %s\n"為format-string參數, 1為%d的參數, abc為%s的參數 printf "%d %s\n" 1 "abc" 輸出: 1 abc
printf的轉義序列
序列 | 說明 |
---|---|
\a | 警告字符,通常為ASCII的BEL字符 |
\b | 后退 |
\c | 抑制(不顯示)輸出結果中任何結尾的換行字符(只在%b格式指示符控制下的參數字符串中有效),而且,任何留在參數里的字符、任何接下來的參數以及任何留在格式字符串中的字符,都被忽略 |
\f | 換頁(formfeed) |
\n | 換行 |
\r | 回車(Carriage return) |
\t | 水平制表符 |
\v | 垂直制表符 |
\\ | 一個字面上的反斜杠字符 |
\ddd | 表示1到3位數八進制值的字符。僅在格式字符串中有效 |
\0ddd | 表示1到3位的八進制值字符 |
實例:
#example1 $ printf "a string, no processing:<%s>\n" "A\nB" a string, no processing:<A\nB> #example2 $ printf "a string, no processing:<%b>\n" "A\nB" a string, no processing:<A B> #example3 $ printf "www.cnblog.com \a" www.cnblog.com $ #不換行
以上就是shell的兩種輸出命令的簡介 :)