在處理伺服器的工作時,為了能自動化完成一些常常會進行的工作,最常用到就是 Linux 的 Shell Script。 ### Linux Shell Linux Shell 就好像的 Window CMD (用 DOS 更為貼切),不同的是 Window CMD 比較像一個軟體,運行在 Window 之上,而 Shell 本身就是的外殼 (所以叫 Shell),它的底下就是 OS 本身了 ! Shell 有好多種,最常見到可能會是 `sh`、`bash`。`bash` 是 `sh` 的子集,並基於 `sh` 上加入了好多功能。 ### 使用 Shell Script 讀取使用者 Input String 我們可以通過使用 `read` 來讀取使用者在 shell 鍵入的字串。我們使用以下的指令建立 `test_command.sh`。 ```sh $ vi test_command.sh ``` 然後輸入以下內容 : ```sh #! /bin/sh printf "Enter you name: " read VARIABLE_NANE printf "\n\nYour name: ${VARIABLE_NANE}" ``` 完成後儲存,並試試運行 : ```sh $ chmod 755 ./test_command.sh $ ./test_command.sh Enter your name: 19Site Your name: 19Site ``` ### 收集 Password 有時我們可能要輸入 Password 來進行動作,但是不又想在畫面上顯示出 Password 的內容,要如何做呢? 我們可以透過修改 Shell 的設定,來把使用者鍵入的字符設為不顯示。我休修改一下上面的 Script。 ```sh #! /bin/sh stty -echo printf "Enter password: " read VARIABLE_NANE stty echo printf "\n\nYour password: ${VARIABLE_NANE}" ``` 我們可以透過使用 `stty` 指令來變更 Shell 的 `echo` 設定,從而達成把輸入隱藏目的。 ```sh $ chmod 755 ./test_command.sh $ ./test_command.sh Enter your password: Your password: 19Site ```