[英]how to call a function with 2 arguments which under the option of “getopts”
Linux bash 腳本中的新功能。 在這里,我嘗試使用getopts
創建一些文件。 例如,我想在命令行中創建 3 個名為 xyzfile 的文件./createfiles -n xyzfile 3
應該給出(選項-n
之后的 2 arguments )。 結果應該是 3 個名為 xyzfile_1、xyzfile_2 和 xyzfile_3 的文件。
我試圖將我的createfile()
function 放在 while 循環之外以及 while 循環內部。 但是選項-n
不起作用。 我還嘗試創建另一個名為foo()
的 function ,其中包含 function createfile()
,但那里仍然有問題。 我不知道我能做什么。 希望能得到大家的一些建議。 非常感謝!
#!/bin/bash
while getopts :n:bc opt; do
case $opt in
n) echo test 3333333
createfile() {
echo "$OPTARG"
sum=$2
for((i=1;i<=sum;i++))
do
touch "$OPTARG_${i}"
done
}
createfile $OPTARG ${2};;
b) echo "test 1111111";;
c) echo "test 2222222";;
*) echo error!;;
esac
done
首先解析選項,然后使用您發現的值。 一個選項只能接受一個參數,因此-n
只獲取第一個參數(我將在此處將其保留為文件名詞干)。 計數將是解析選項后找到的普通位置參數。
while getopts :n:bc opt; do
case $opt in
n) stem=$OPTARG; shift 2;;
b) shift 1;;
c) shift 1;;
*) shift 1; echo error ;;
esac
done
count=${1?No count given}
createfile () {
for ((i=$1; i<=$2; i++)); do
touch "${1}_${i}"
done
}
createfile "$stem" "$count"
使用單獨的選項進行計數,並在選項處理后創建文件。
就像是:
while getopts "n:c:" opt; do
case $opt in
n) name="$OPTARG";;
c) count=$OPTARG;;
# other options...
esac
done
shift $((OPTIND -1))
while (( count > 0 )); do
touch "${name}_$count"
(( count-- ))
# ...
done
getopts
僅支持不帶或帶一個參數的選項。 所以你必須決定你希望你的腳本以哪種方式工作。 您有多種選擇:
-m
或類似選項以傳遞要創建的最大文件數: createfile -n xyzfile -m 3
createfile 3 -n xyzfile
或createfile -n xyzfile 3
的含義相同。 在我的腳本中,如果用戶總是需要傳遞一個選項,我經常使用這樣的位置參數。createfile xyzfile -n 3
甚至createfile xyzfile
,其中名稱是位置參數,文件數是可選的(選擇一個邏輯默認值,可能是 1)...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.