輸出帶有轉義字符的內容
單獨一個echo表示一個換行
使用echo輸出時,每一條命令之后,都默認加一個換行;要想取消默認的換行,需要加 -n 參數。
#!/bin/bash #文件名:test.sh echo "aaaaaaaaaaa" echo "bbbbbbbbbbb" echo -n "ccccccccccc" echo "ddddddddddd"
運行腳本:
ubuntu@ubuntu:~$ ./test.sh aaaaaaaaaaa bbbbbbbbbbb cccccccccccddddddddddd ubuntu@ubuntu:~$
使用雙引號括起來的內容中有轉義字符時,在添加參數 -e 之后才會被轉義,否則會原樣輸出。
#!/bin/bash #文件名:test.sh echo "hello\n world" echo -e "hello\n world"
運行腳本:
ubuntu@ubuntu:~$ ./test.sh hello\n world hello world ubuntu@ubuntu:~$
讀取用戶輸入:
方式一:
#!/bin/bash #文件名:test.sh echo -n "please input your name and age:" read name age echo "welcome $name, your age is $age"
方式二:
#!/bin/bash #文件名:test.sh read -p "please input your name and age:" name age echo "welcome $name, your age is $age"
讀入的內容會自動保存到變量中去,可以直接使用變量獲取輸入的值。
執行上面兩個腳本,結果都為:
ubuntu@ubuntu:~$ ./test.sh please input your name:beyond 10 welcome beyond, your age is 10 ubuntu@ubuntu:~$
改變字體顏色:
以 \e[前景顏色;背景顏色m 開頭,中間為內容,然后以 \e[0m結束,0m表示將顏色恢復為默認的顏色,如果不加0m,則之后的所有輸出都將使用前面的設置。
其中使用字母m來分隔轉義字符和內容。同時輸出的時候,因為有轉義字符,所以要加-e參數
\e可以使用八進制的\033代替。
顏色表:
字體顏色 | 黑30 | 紅31 | 綠32 | 棕33 | 藍34 | 紫35 | 青36 | 白37 |
背景顏色 | 黑40 | 紅41 | 綠42 | 棕43 | 藍44 | 紫45 | 青46 | 白47 |
#!/bin/bash #文件名:test.sh echo -e "\e[32;40m this is test \e[0m"; echo -e "\e[33;47m this is test \e[0m"; echo -e "\033[32;40m hello world \033[0m"; echo -e "\033[33;47m hello world \033[0m";
運行結果: