# week1 挑戰題系列-shell script shell script 是利用 shell 的功能所寫的一個程式 (program),這個程式是使用純文字檔,將一些 shell 的語法與指令(含外部指令)寫在裡面。 shell 則是負責溝通 application 和 kernel 之間的 middle man,其中 shell 的種類有:bash、sh (Bourne shell)...等,使用的語法也會有差異。 ## 變數的宣告 & 呼叫方式 **宣告變數的時候,等號兩邊不能直接接空白字元** ``` var1=hello echo ${var1} //呼叫變數的方法 => ${變數名稱} 得到hello ``` ``` var1=$(命令式) 把命令式的執行結果輸出到變數 ``` ### 如果有特殊符號想要跳脫的話,使用`\殊符號` `\`會讓後面一個特殊符號被跳脫,例如↓ ``` var2=123\/123\"\"123 echo ${var2} 得到 123/123""123 ``` ### unset 取消變數 `unset var1` ### 將 parameter 傳到 script file 裡面 透過在 script file 後面直接輸入 parameter 來達成,根據輸入的 parameter 先後順序會用不同的預設變數來表示,例如↓ ``` scriptname opt1 opt2 opt3 opt4 $0 $1 $2 $3 $4 ``` ## sed 的使用 sed 是一個支援正規表達式的程式/指令,通常用在需要以"行"為單位處理 某個 文字file 的時候使用。 例如:只印出有被使用到的行(`-n`),印出第 20 行('20p'),處理的檔案是 `${1}`。 `sed -n '20p' ${1}` ## cut 的使用 cut 指令可以將一段訊息的某一段給他 切 出來,處理的訊息是以『行』為單位。 例如:用 `"`作為分隔符號(`-d '"'`),再把第 4 個分隔區塊切出來(`-f 4``) `sed -n '20p' ${1}| cut -d '"' -f 4` ## 補充 有實際用到的↓ * [學習 Shell Scripts](https://linux.vbird.org/linux_basic/centos7/0340bashshell-scripts.php) * [How to read a file into a variable in shell?](https://stackoverflow.com/questions/7427262/how-to-read-a-file-into-a-variable-in-shell) * [grep on a variable](https://unix.stackexchange.com/questions/163810/grep-on-a-variable) * [Linux 指令 SED 用法教學、取代範例、詳解](https://terryl.in/zh/linux-sed-command/#p-) 沒有用到的↓ * [簡明 Linux Shell Script 入門教學](https://blog.techbridge.cc/2019/11/15/linux-shell-script-tutorial/) * [簡易 Regular Expression 入門指南](https://blog.techbridge.cc/2020/05/14/introduction-to-regular-expression/)