shell指令碼中的變數
在shell指令碼中使用變數顯得我們的指令碼更加專業更像是一門語言,開個玩笑,變數的作用當然不是為了專業。如果你寫了一個長達1000行的shell指令碼,並且指令碼中出現了某一個命令或者路徑幾百次。突然你覺得路徑不對想換一下,那豈不是要更改幾百次?你固然可以使用批量替換的命令,但是也是很麻煩,並且指令碼顯得臃腫了很多。變數的作用就是用來解決這個問題的。
來看一個示例:
#! /bin/bash ## author:Xiong Xuehao ## This is my first shell script. Using variables in scripts. d1=`date +%H:%M:%S`echo "The script begin at $d1" echo "now we will sleep 2 seconds" sleep 2 d2=`date +%H:%M:%S` echo "The script end at $d2"
在myfirstbash_002.sh中使用到了反引號(TAB鍵上方,1/!鍵左邊的那個鍵),你是否還記得它的作用?’d1’和’d2’在指令碼中作為變量出現,定義變數的格式為“變數名=變數的值”。當在指令碼中引用變數時需要加上’$’符號。下面看看指令碼執行結果吧:
案例1:在shell指令碼中使用數學計算
下面我們用shell計算兩個數的和。
#! /bin/bash ## author:Xiong Xuehao ## This is my first shell script. Calculate the sum of two numbers. x=1 y=2 sum=$[$x+$y] echo "$x + $y sum is $sum"
數學計算要用’[ ]’括起來並且外頭要帶一個’$’。指令碼結果為:
案例2:Shell指令碼還可以和使用者互動
Shell指令碼和使用者互動:
#! /bin/bash ## author:Xiong Xuehao ## This is my first shell script. Use readin the script. echo "Please input a number:" read x echo "Please input another number:" read y sum=$[$x+$y] echo "$x + $y sum is $sum"
這就用到了read命令了,它可以從標準輸入獲得變數的值,後跟變數名。”read x”表示x變數的值需要使用者通過鍵盤輸入得到。指令碼執行過程如下:
我們不妨加上-x選項再來看看這個執行過程:
在myfirstbash_004.sh中還有更加簡潔的方式:
#! /bin/bash ## author:Xiong Xuehao ## This is my first shell script. Use read in the script. read -p "Please input a number:" x read -p "Please input another number:" y sum=$[$x+$y] echo "$x + $y sum is $sum"
read -p 選項類似echo的作用。執行如下:
案例3:Shell指令碼預設變數
你有沒有用過這樣的命令”/etc/init.d/iptables restart “ 前面的/etc/init.d/iptables 檔案其實就是一個shell指令碼,為什麼後面可以跟一個”restart”? 這裡就涉及到了shell指令碼的預設變數。實際上,shell指令碼在執行的時候後邊是可以跟變數的,而且還可以跟多個。示例:
#! /bin/bash ## author:Xiong Xuehao ## This is my first shell script. Use preset variables. sum=$[$1+$2] echo "$1 + $2 sum is $sum"
執行過程如下:
在指令碼中,你會不會奇怪,哪裡來的$1和$2,這其實就是shell指令碼的預設變數,其中$1的值就是在執行的時候輸入的1,而$2的值就是執行的時候輸入的$2,當然一個shell指令碼的預設變數是沒有限制的,這回你明白了吧。另外還有一個$0,不過它代表的是指令碼本身的名字。