0

I'm trying to learn to use the getopts() feature in bash to parse my arguments, but my program requires that in addition to my standard -a -b -c type arguments I also need to get any number of files to work on, and I can't find any information on how to make getopts recognize them instead of throwing them out as invalid arguments. Here's an example:

while getopts "a:b:c:d" flag
do

    echo Doing: "$flag" $OPTIND $OPTARG

    if [ "$flag" = a ]; then
        first="$OPTARG"
        echo Found argument: $first
    fi

... and so on with other if statements. This works great if my program just needed a command like: program -a -c , but instead I need to take in something like: program -a file.sh -c otherfile.sh.

Can somebody show me an example of how to do something like this?

4

2 回答 2

2

这是我的一个 shell 脚本的片段,它getopts或多或少地使用和执行您想要做的事情:

arg0=$(basename $0 .sh)

usage()
{
    echo "Usage: $arg0 [-qvF] [-s suffix] -j jdcfile file.msd" 1>&2
    exit 1
}

error()
{
    echo "$arg0: $*" 1>&2
    exit 1
}

Fflag=
suffix=
jdcfile=
qflag=
vflag=no
while getopts Fj:qs:v opt
do
    case "$opt" in
    (F) Fflag="-F";;
    (j) jdcfile="$OPTARG";;
    (q) qflag="-q";;
    (s) suffix="$OPTARG";;
    (v) vflag=yes;;
    (*) usage;;
    esac
done

shift $(($OPTIND - 1))

case $# in
(1) : OK;;
(*) usage;;
esac

if [ -z "$jdcfile" ]
then error "you did not specify which jdcfile to use (-j option)"
fi

msd_file=$1

我认为这shift是您缺少的部分。getopts那以及在处理循环之后对命令行上剩余参数的后续处理。

在这个特定程序的最后"$@",应该处理一个文件名。对于此特定程序,没有文件或列出多个文件是错误的。您可以删除该最终版本case或对其进行修改以满足您的需要。此代码还强制执行-j jdcfile“选项”;它是一个强制参数,如使用消息中所示。

之后的一个更典型的模式shift是:

for file in "$@"
do
    ...processing of $file...
done

这只是让您处理零文件名的情况。

errorusage函数也是有用的大纲/原型。:如评论中所述,如果您希望在选项字符串上使用前导,您可以负责错误处理。我选择不这样做,但我忘记了这是我做出的决定。

于 2012-05-28T19:11:47.077 回答
0

根据我上面的评论 - 你不想要getopts这个。一种更简单的方法将起作用:

#!/bin/bash

args=()

for arg in "$@"
do
  case "$arg" in
    "-a" )
      echo "We have an '-a'!"
      ;;
    "-b" )
      echo "We have a '-b'!"
      ;;
    * )
      args+=($arg)
  esac
done

echo And we have these arguments: ${args[*]}

要查看它运行:

$ ./program one -a two three -b four
We have an '-a'!
We have a '-b'!
And we have these arguments: one two three four
于 2012-05-28T19:29:51.700 回答