如何在Bash指令碼中使用命令列引數
簡介
通常,有很多方法可以向程式設計或指令碼語言傳遞輸入,有時需要從命令列而不是從程式碼中傳遞輸入。像任何其他程式設計或指令碼語言一樣,bash指令碼也支援命令列引數。
在本文中,我們將嘗試探討命令列引數的語法,然後我們將檢視一些命令列引數的示例,並討論特殊變數。
命令列引數語法
我們已經知道如何在Linux中執行bash指令碼。我們可以使用bash或sh命令,然後是bash檔名。
現在,要傳遞命令列引數,我們可以使用空格分隔的引數。
bash <bash script file name> <command line argument 1> <command line argument 2> … <command line argument n>
這是一個實際的例子
bash add.sh 1 2 3
接下來,我們將嘗試一些命令列引數bash指令碼。
方法一:透過命令列傳遞三個整數並求和
示例
#!/bin/bash echo "First argument is--> $1" echo "Second argument is--> $2" echo "Third argument is--> $3" sum=$((1+$2+$3)) echo "Sum = $sum"
然後像這樣執行bash指令碼:
$ bash sum.sh 1 2 12
輸出
First argument is--> 1 Second argument is--> 2 Third argument is--> 12 Sum = 15
解釋
從上面的指令碼中,我們得到了以下幾點
第一個引數儲存在$1中
第二個引數儲存在$2中
第三個引數儲存在$3中
方法二:bash指令碼中使用的特殊變數列表
$1…$n − 這是位置引數。我們已經從前面的例子中知道了這一點。
$0 − 這表示指令碼檔名。例如:sum.sh
$# − 這包含傳遞的引數總數。
$@ − 這包含每個引數的值。
$$ − 這包含當前shell的PID。
$* − 使用此方法,我們可以獲得單個引數中的所有引數。
$? − 這包含最近命令的退出狀態ID。
$! − 這包含最近命令的PID。
讓我們在一個指令碼中使用所有這些並檢視輸出。
示例
#!/bin/bash echo "1. 1st argument is --> $1" echo -e "1. 2nd argument is --> $2" echo "2. File name is --> $0" echo "3. Total number of arguments passed --> $#" echo "4." i=1; for arg in "$@" do echo "argument-$i is : $arg"; i=$((i + 1)); done echo "5. PID of current shell --> $$" echo "6." i=1; for arg in "$*" do echo "argument-$i is: $arg"; i=$((i + 1)); done echo "Executing ls command" ls echo "7. Exit status of last command --> $?" echo "Executing firefox command" firefox & echo "8. PID of last command --> $!" killall firefox
輸出
$ bash special-var.sh 1 "2 4" 5 1. 1st argument is --> 1 1. 2nd argument is --> 2 4 2. File name is --> special-var.sh 3. Total number of arguments passed --> 3 4. argument-1 is : 1 argument-2 is : 2 4 argument-3 is : 5 5. PID of current shell --> 3061 6. argument-1 is: 1 2 4 5 Executing ls command special-var.sh sum.sh 7. Exit status of last command --> 0 Executing firefox command 8. PID of last command --> 3063
方法三:標誌的使用
有一種方法可以與標誌一起傳遞命令列引數。標誌是在引數之前帶有連字元的單個字母。
讓我們看看程式碼,然後就很容易理解這個概念了。
示例
#!/bin/bash
while getopts c:s:d: flag
do
case "${flag}" in
d) district=${OPTARG};;
s) state=${OPTARG};;
c) country=${OPTARG};;
esac
done
echo "District: $district";
echo "State: $state";
echo "Country: $country";
輸出
$ bash flag.sh -c INDIA -d BANGALORE -s KARNATAKA District: BANGALORE State: KARNATAKA Country: INDIA
從上面的程式碼中,我們可以看到在命令列中使用標誌的優點。現在我們知道,我們不必按順序傳遞命令列引數。相反,我們可以使用標誌。
結論
在本文中,我們學習瞭如何在Linux的bash指令碼中使用命令列引數。此外,各種特殊變數有助於解析命令列引數。因此,使用命令列引數,我們可以進行更好、更高效的bash指令碼編寫。
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP