iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 24
1
Software Development

如何使用 Linux 從土裡到冒出頭來系列 第 24

Day 24 Sell Script(2)

Day 24 Shell Script(2)

昨天介紹了 echo、變數、比較運算 等指令使用,今天就來直接實做吧!

小試身手

建立一個簡單的 shell scipt 。

建立檔案

[root@localhost ~]# touch demo.sh

編輯 demo.sh

[root@localhost ~]# vi demo.sh

demo.sh
輸入以下內容:

#!/bin/bash

echo -n "請您選擇一個數值(0 or 1):"
read result

if test $result -eq "1"
then
        echo "帥哥您好"
else
        echo "美女您好"
fi

輸入完以後儲存
Esc 鍵 > 輸入:wq > Enter

  • 第1行 宣告使用 /bin/bash 來執行 shell script ,這個一定要宣告的。
  • 第3行 -n 印出訊息文字
  • 第4行 讀取並設定變數名稱為 $result, 輸入字串內容的動作 是在執行這支 script 時輸入。
  • 第6行 $result 變數 比對 是否為等於 1
  • 第7、8行 比對如果等於1 就印出字串
  • 第9、10行 否則則印出第10行。

使用 bash 指令 執行 demo.sh

[root@localhost ~]# bash demo.sh
請您選擇一個數值(0 or 1):1
帥哥您好

[root@localhost ~]# bash demo.sh
請您選擇一個數值(0 or 1):0
美女您好

宣告 shell

在每一個 script 內容裡面,第一行基本上要定義此 script 要使用哪一種 shell,由於每一個 shell 有的語法不同、有的相同,所以確保及指定是必要的。

  • #!/bin/sh
  • #!/bin/bash

有人一定會很好奇,宣告的第一字是「#」,在Shell Script中,「#」表示註解,在 # 後面將視為註解並且被程式忽略,但是「#」「!」放在一起的意思就不一樣了,「#!」放在一起,有著標示用什麼東西的作用。但如果一支script,裡面只單純寫 Linux 的指令,其實可以不用宣告用哪個 shell,但還是會建議統一都寫比較清楚。


上一篇
Day 23 Sell Script(1)
下一篇
Day 25 正規化表示
系列文
如何使用 Linux 從土裡到冒出頭來30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言