Linux之向指令碼傳引數

2021-04-02 22:30:53 字數 1197 閱讀 3878

linux之向指令碼傳引數

之前我們向指令碼傳遞引數可以通過$1,$2等特殊變數。很方便,但是有些限制,就是不能超過9個引數。通過使用shift和getopts命令,我們可以十分方便的向指令碼傳遞引數。

一、shift

通過使用shift,我們將引數選項從左向右移。

看下面這個例子:

#!/bin/sh

# shift_sample

if [ $# -lt 1 ]

echo "too few params"

exit 1

fiwhile [ $# -ne 0 ]

doecho $1

shift

done

在命令列下輸入:

#:shift_sample one two three

輸出結果如下:

onetwo

three

二、getopts

如果你的指令碼命令後有一些選項開關,比如-i,-c等等,這個時候使用shift來挨個檢視比較麻煩。而用getopts則比較方便。

getopts使用格式如下:

getopts format_string variable

還是看乙個例子:

#!/bin/sh

#getopts_sample

if [ $# -lt 1 ]

echo "too few params"

exit 1

fiwhile getopts hv option

docase $option in

h)echo "this is help information"

;;v)echo "the version is 1.0.0"

;;done

這段指令碼允許兩個引數選項,分別是-h,-v,使用的時候可以分開來寫,像-h -v,也可以連在一起,像-hv。

在命令列下輸入:

#:getopts_sample -h -v

輸出:this is help information

the version is 1.0.0

如果選項需要輸入值,則在引數選項後面加上:,比如:

getopts hvc: option

這個時候呼叫該指令碼,則使用如下格式:

getopts_sample -h -v -c hello

指令碼在讀到-c的時候,會把它的值儲存在$optarg變數中。

Linux之向指令碼傳引數

linux之向指令碼傳引數 之前我們向指令碼傳遞引數可以通過 1,2等特殊變數。很方便,但是有些限制,就是不能超過9個引數。通過使用shift和getopts命令,我們可以十分方便的向指令碼傳遞引數。一 shift 通過使用shift,我們將引數選項從左向右移。看下面這個例子 bin sh shif...

向shell指令碼傳引數

執行 nano test.sh 建立乙個新的shell指令碼。指令碼test.sh的內容如下 bin sh name 1 echo the are great man 給新建立的test.sh的指令碼賦可執行許可權,命令為 chmod 755 test.sh 執行 test.sh xiao wang...

向Process傳引數

摘要 有的時候,我們需要在乙個程序啟動另外乙個程序,並傳遞一些引數過去。正文 我們很容易會想到下面的 processstartinfo startinfo new processstartinfo startinfo.filename d test.exe startinfo.arguments s...