【问题标题】:How do I separate the first argument from that of getopts?如何将第一个参数与 getopts 的参数分开?
【发布时间】:2011-10-06 15:07:32
【问题描述】:
#!/bin/bash

priority=false
it=0
dir=/

while getopts  "p:i" option
do
  case $option in
         i) it=$OPTARG;;
         p) priority=true;;
   esac
done

if [[ ${@:$OPTIND} != "" ]]
then
    dir=${@:$OPTIND}
fi
echo $priority $it $dir

如果我执行它,我会得到2 testDir 对应$dir0 对应$it,而不仅仅是testDir 对应$dir2 对应$it。如何获得预期的行为?

./test.sh -pi 2 testDir
true 0 2 testDir

【问题讨论】:

  • 如果你使用 -p 2 -i testDir 你会得到你想要的行为吗?
  • 运行 bash -x ./test.sh 以查看您的脚本在做什么。 if 块看起来很奇怪:这意味着如果有一个非空的非选项参数,则将 dir 设置为对非选项参数执行路径名扩展和分词并用空格连接它们的结果。 (很复杂,嗯?)我怀疑你的意思是if [[ ${!OPTIND} != "" ]]; then dir=${!OPTIND}; fi。常用的方法更简单:解析选项后运行shift $OPTIND,使得非选项参数为$1$2等,即if [[ -n $1 ]]; then dir=$1; fi

标签: bash parameter-passing command-line-arguments getopts


【解决方案1】:

我会这样写:

#!/bin/bash

priority=false
it=0

while getopts ":hpi:" opt; do
    case "$opt" in
        h) echo "usage: $0 ...."; exit 0 ;;
        p) priority=true ;;
        i) it="$OPTARG" ;;
        *) echo "error: invalid option -$OPTARG"; exit 1 ;;
    esac
done

shift $(( OPTIND - 1 ))

dir="${1:-/}"

echo "priority=$priority"
echo "it=$it"
echo "dir=$dir"

【讨论】:

    【解决方案2】:

    您似乎将 getopts 的 optstring 参数设置错了。你有p:i,而你想要的是pi:,所以-i 开关接受参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 2018-03-04
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      相关资源
      最近更新 更多