0

我还有另一个我根本无法解决的 bash 脚本问题。这是我的简化脚本显示了问题:

while getopts "r:" opt; do
case $opt in

  r)
    fold=/dev
    dir=${2:-fold}

     a=`find $dir -type b | wc -l`
     echo "$a"
  ;;
esac
done

我通过以下方式调用它:

  ./sc.sh -r /bin

它可以工作,但是当我不提供参数时它不起作用:

  ./sc.sh -r

我希望 /dev 成为此脚本中的默认参数 $2 。

4

2 回答 2

2

前面可能还有其他参数,不要硬编码参数号($2)。

getopts 帮助说

当一个选项需要一个参数时,getopts 将该参数放入 shell 变量 OPTARG。
...
[在静默错误报告模式下,] 如果找不到所需的参数,getopts 会在 NAME 中放置一个 ':' 并将 OPTARG 设置为找到的选项字符。

所以你要:

dir=/dev                            # the default value
while getopts ":r:" opt; do         # note the leading colon
    case $opt in
        r) dir=${OPTARG} ;;
        :) if [[ $OPTARG == "r" ]]; then
               # -r with required argument missing.
               # we already have a default "dir" value, so ignore this error
               :
           fi
           ;;
    esac
done
shift $((OPTIND-1))

a=$(find "$dir" -type b | wc -l)
echo "$a"
于 2014-02-11T17:51:19.413 回答
0

这对我有用:

#!/bin/bash

while getopts "r" opt; do
case $opt in

  r)
    fold=/dev
    dir=${2:-$fold}

     echo "asdasd"
  ;;
esac
done

删除 getopts 参数中的冒号 ( :)。这导致 getopt 期待一个论点。(有关 getopt 的更多信息,请参见此处)

于 2014-02-11T17:27:17.260 回答