在 Unix 式作業系統中,最重要的特性之一就是命令列介面,也就是 shell。shell 環境讓使用者能與作業系統的核心功能互動,而所謂腳本,正是建立在這種環境之上。腳本通常使用某種基於解釋器的編程語言,本質上就是一個個檔案,我們把一系列要執行的命令寫進去,再交由 shell 執行。目前大多數 GNU/Linux 系統預設的 shell 是 bash。
打開終端後會出現提示符:
[root@localhost ~]#
其中 root 是用戶名;# 代表管理員用戶 root,$ 代表普通用戶。
shell 腳本通常以 shebang 起始,例如:
#!/bin/bash 其中 #! 位於解釋器路徑之前,/bin/bash 是 Bash 的解釋器命令路徑。
運行腳本有兩種方式:(1)把腳本作為 bash 的命令行參數,即 bash 文件名;(2)賦予腳本可執行權限後再執行:chmod +x 文件名,然後 文件路徑/文件名。
echo 是最基本的打印命令,預設執行後會換行。以下三種寫法都能成功輸出,但各有細微差別:
[root@localhost ~]# echo hello world hello world [root@localhost ~]# echo "hello world" hello world [root@localhost ~]# echo 'hello world' hello world
如果想打印感嘆號 !,就不能把它放進雙引號裡,可以在前面加轉義字符 \ 或直接輸出:
[root@localhost ~]# echo ! ! [root@localhost ~]# echo \! ! [root@localhost ~]# echo "!" bash: !: event not found [root@localhost ~]# echo '\!' \!
若輸出的語句帶有分號 ;,也不能直接輸出,否則分號會被當作命令分隔符:
[root@localhost ~]# echo "hello;world" hello;world [root@localhost ~]# echo 'hello;world' hello;world [root@localhost ~]# echo hello;world hello bash: world: command not found
printf 預設執行後不換行,且不帶引號輸出時,無法直接輸出帶空格的語句:
[root@localhost ~]# printf "hello world" hello world[root@localhost ~]# printf hello world hello[root@localhost ~]# printf helloworld helloworld[root@localhost ~]# printf 'hello world' hello world[root@localhost ~]# printf hello world hello
printf 還可以定義輸出格式,例如:
[root@localhost ~]# printf '%-5s %-10s\n' 123 456 123 456 [root@localhost ~]# printf "%-5s %-10s\n" 123 456 123 456
理解 echo 與 printf 在引號、轉義與換行上的差異,是編寫可靠 Shell 腳本的第一步。