位置參數變量是標準的數字:$0是程序名,$1是第一個參數,$2,是第二個參數,直到第九個參數$9。node
每一個參數必須用空格分開。固然若是要在參數中引用空格必須加引號。shell
[root@node1 ljy]# more ceshi.sh #!/bin/bash sum=$[ $1 + $2 ] echo "first num is $1" echo "second num is $2" echo "sum num is $sum" [root@node1 ljy]# sh ceshi.sh 2 3 first num is 2 second num is 3 sum num is 5
$0能夠獲取shell在命令行啓動的腳本名bash
[root@node1 ljy]# more ceshi.sh #!/bin/bash echo "this script name is $0" [root@node1 ljy]# sh ceshi.sh this script name is ceshi.sh
若是使用另外一些命令執行腳本,可能命令會與腳本名混在一塊兒。ide
[root@node1 ljy]# more ceshi.sh #!/bin/bash echo "this script name is $0" [root@node1 ljy]# sh /ljy/ceshi.sh this script name is /ljy/ceshi.sh [root@node1 ljy]# ./ceshi.sh this script name is ./ceshi.sh
basename命令能夠返回不包含路徑的腳本名測試
[root@node1 ljy]# more ceshi.sh #!/bin/bash name=$(basename $0) echo "this script name is $name" [root@node1 ljy]# sh /ljy/ceshi.sh this script name is ceshi.sh [root@node1 ljy]# ./ceshi.sh this script name is ceshi.sh
若是你要使用命令行參數,而不當心漏了加,可能就要報錯了,this
因此最好加一個測試命令行
-n測試來檢查命令行參數是否有數據。blog
[root@node1 ljy]# more ceshi.sh #!/bin/bash if [ -n "$1" ] && [ -n "$2" ] then sum=$[ $1 + $2 ] echo "first num is $1" echo "second num is $2" echo "sum num is $sum" else echo "you should identify yourself!" fi [root@node1 ljy]# sh ceshi.sh 1 2 first num is 1 second num is 2 sum num is 3 [root@node1 ljy]# sh ceshi.sh 1 you should identify yourself!
$#含有腳本運行時攜帶的命令行參數的個數。能夠在腳本中任何地方使用這個變量。ip
[root@node1 ljy]# more ceshi.sh #!/bin/bash echo there were $# parameters [root@node1 ljy]# sh ceshi.sh 1 2 2 3 there were 4 parameters
if-then語句經常使用-ne來測試命令行參數數量。字符串
$*和$@會將命令行提供的全部參數做爲一個單詞保存。
$@變量會將全部參數當作一個字符串的多個獨立的單詞。
$*變量會將全部參數當成單個參數。
read命令從標準輸入或者另外一個文化描述符中接受輸入,收到輸入後,read命令會將數據放在一個變量裏。
[root@node1 ljy]# more ceshi.sh #!/bin/bash echo -n "enter your name:" read name echo hello $name [root@node1 ljy]# sh ceshi.sh enter your name:ljy hello ljy
-n選項不會在字符末尾輸出換行符,容許用戶緊跟其後的輸入數據。
-p命令容許你輸入提示符:
使用read命令可能會致使程序一直等待中。
你能夠使用-t選項來指定一個定時器。
[root@node1 ljy]# more ceshi.sh #!/bin/bash if read -t 5 -p "enter your name:" name then echo "your name is $name" else echo echo "sorry,slow" fi [root@node1 ljy]# sh ceshi.sh enter your name: sorry,slow
-s選項能夠避免輸入的內容顯示在屏幕上
[root@node1 ljy]# more ceshi.sh #!/bin/bash read -s -p "enter your name:" name echo echo "your name is $name" [root@node1 ljy]# sh ceshi.sh enter your name: your name is ljy
每次調用一次read命令,都會從文件中讀取一行數據,一直到沒有內容的時候,read命令會退出並返回非零退出碼。
[root@node1 ljy]# more ceshi.sh #!/bin/bash count=1 cat test.txt | while read line do echo line:$line done [root@node1 ljy]# sh ceshi.sh line:1 line:2 line:3 line:4 line:5 line:
空格也做爲一行顯示出來了。