簡體   English   中英

如何在“getopts”選項下使用 2 個 arguments 調用 function

[英]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
  • 您還可以使用未作為選項傳遞的 arguments,如果您的解析做得好,那么createfile 3 -n xyzfilecreatefile -n xyzfile 3的含義相同。 在我的腳本中,如果用戶總是需要傳遞一個選項,我經常使用這樣的位置參數。
  • 您甚至可以考慮將調用腳本的方式更改為createfile xyzfile -n 3甚至createfile xyzfile ,其中名稱是位置參數,文件數是可選的(選擇一個邏輯默認值,可能是 1)...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM