echo string
echo "It is a test"
這裏的雙引號徹底能夠省略,如下命令與上面實例效果一致:shell
echo It is a test
echo "\"It is a test\"" #結果將是: #"It is a test"
#!/bin/sh read name echo "$name It is a test"
[root@www ~]# sh test.sh OK #標準輸入 OK It is a test #輸出
echo -e "OK! \n" # -e 開啓轉義 echo "It is a test" # 輸出結果: # OK! # # It is a test
#!/bin/sh echo -e "OK! \c" # -e 開啓轉義 \c 不換行 echo "It is a test" # 輸出結果: # # OK! It is a test
echo "It is a test" > myfile
echo '$name\"' #輸出結果: #$name\"
echo `date` #注意: 這裏使用的是反引號 `, 而不是單引號 '。 #結果將顯示當前日期 #Thu Jul 24 10:08:46 CST 2014
printf
命令的語法:printf format-string [arguments...]bash
$ echo "Hello, Shell" Hello, Shell $ printf "Hello, Shell\n" Hello, Shell
#!/bin/bash printf "%-10s %-8s %-4s\n" 姓名 性別 體重kg printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234 printf "%-10s %-8s %-4.2f\n" 楊過 男 48.6543 printf "%-10s %-8s %-4.2f\n" 郭芙 女 47.9876
姓名 性別 體重kg 郭靖 男 66.12 楊過 男 48.65 郭芙 女 47.99
更多實例:code
#!/bin/bash # format-string爲雙引號 printf "%d %s\n" 1 "abc" # 單引號與雙引號效果同樣 printf '%d %s\n' 1 "abc" # 沒有引號也能夠輸出 printf %s abcdef # 格式只指定了一個參數,但多出的參數仍然會按照該格式輸出,format-string 被重用 printf %s abc def printf "%s\n" abc def printf "%s %s %s\n" a b c d e f g h i j # 若是沒有 arguments,那麼 %s 用NULL代替,%d 用 0 代替 printf "%s and %d \n"
執行腳本,輸出結果以下所示:orm
1 abc 1 abc abcdefabcdefabc def a b c d e f g h i j and 0
序列 | 說明 |
---|---|
\a | 警告字符,一般爲ASCII的BEL字符 |
\b | 後退 |
\c | 抑制(不顯示)輸出結果中任何結尾的換行字符(只在%b格式指示符控制下的參數字符串中有效),並且,任何留在參數裏的字符、任何接下來的參數以及任何留在格式字符串中的字符,都被忽略 |
\f | 換頁(formfeed) |
\n | 換行 |
\r | 回車(Carriage return) |
\t | 水平製表符 |
\v | 垂直製表符 |
\\ | 一個字面上的反斜槓字符 |
\ddd | 表示1到3位數八進制值的字符。僅在格式字符串中有效 |
\0ddd | 表示1到3位的八進制值字符 |
$ printf "a string, no processing:<%s>\n" "A\nB" a string, no processing:<A\nB> $ printf "a string, no processing:<%b>\n" "A\nB" a string, no processing:<A B> $ printf "www.runoob.com \a" www.runoob.com $ #不換行