当第一个选项是bash中的路径时,getopts

时间:2014-10-21 19:04:18

标签: bash getopts

我在bash脚本中遇到了getopts问题。基本上我的脚本必须用以下内容调用:

./ myScript / path / to / a / folder -a -b

我的代码顶部是:

while getopts ":ab" opt; do
 case $opt in
  a) 
   variable=a
   ;;
  b)    
   variable=b
   ;;
  \?)
   echo "invalid option -$OPTARG"
   exit 0
 esac
done

echo "$variable was chosen"

现在,只要我在没有/ path / to / a /文件夹的情况下调用我的脚本就可以了。我怎样才能让它与它一起工作呢?

非常感谢

1 个答案:

答案 0 :(得分:1)

如果必须在参数之前放置一个路径,请使用shift command弹出第一个位置参数,并将其余参数保留为getopts。

# Call as ./myScript /path/to/a/folder -a -b

path_argument="$1"
shift   # Shifts away one argument by default

while getopts ":ab" opt; do
 case $opt in
  a) 
   variable=a
   ;;
  b)    
   variable=b
   ;;
  \?)
   echo "invalid option -$OPTARG"
   exit 0
 esac
done

echo "$variable was chosen, path argument was $path_argument"

正如Etan提到的那样,更标准的答案是在选项之后放置非选项参数。更喜欢这种风格,因为它使您的脚本与内置的POSIX选项解析更加一致。

# Call as ./myScript -a -b /path/to/a/folder 

while getopts ":ab" opt; do
 case $opt in
  a) 
   variable=a
   ;;
  b)    
   variable=b
   ;;
  \?)
   echo "invalid option -$OPTARG"
   exit 0
 esac
done
shift $((OPTIND - 1))  # shifts away every option argument,
                       # leaving your path as $1, and every
                       # positional argument as $@
path_argument="$1"
echo "$variable was chosen, path argument was $path_argument"