繁体   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