0

我试图弄清楚如何使用 bash getopts 来处理命令行。我有以下代码:

    while getopts "e:n:t:s:h" opt
        do

            echo $opt
        done

我用这样的 bash 命令行调用它:

. ./testopts.sh -e MyE -s sanctity

什么都没有打印出来。

请帮忙

4

3 回答 3

2

$opt只会打印开关es为您打印,但要打印您还需要回显的传递参数$OPTARG

像这个脚本:

while getopts "e:n:t:s:h" opt
do
   echo $opt $OPTARG
done
于 2013-07-08T18:18:46.870 回答
1

这是我用于参数处理的模板。

它远非最佳(例如使用过多的 sed,而不是内置的 bash 正则表达式等),但您可以将其用于开始:

#!/bin/bash

#define your options here
OPT_STR=":hi:o:c"

#common functions
err() { 1>&2 echo "$0: Error: $@"; return 1; }
required_arg() { err "Option -$1 need argument"; }
checkarg() { [[ "$1" =~ ${optre:--} ]] && { required_arg "$2"; return 1; } || { echo "$1" ; return 0; } }
phelp() { err "Usage: $0" "$(sed 's/^://;s/\([a-zA-Z0-9]\)/ -&/g;s/:/ [arg] /g;s/  */ /g' <<< "$OPT_STR")"; return 1; }

do_work() {
    echo "Here should go your script for processing $1"
}

## MAIN
declare -A OPTION
optre=$(sed 's/://g;s/.*/-[&]/' <<<"$OPT_STR")
while getopts "$OPT_STR" opt;
do
    #change here i,o,c to your options
    case $opt in
    i) OPTION[$opt]=$(checkarg "$OPTARG" $opt) || exit 1;;
    o) OPTION[$opt]=$(checkarg "$OPTARG" $opt) || exit 1;;
    c) OPTION[$opt]=1;;
    h) phelp || exit 1;;
    :) required_arg "$OPTARG" || exit 1 ;;
    \?) err "Invalid option: -$OPTARG" || exit 1;;
    esac
done

shift $((OPTIND-1))
#change here your options...
echo "iarg: ${OPTION[i]:-undefined}"
echo "oarg: ${OPTION[o]:-undefined}"
echo "carg: ${OPTION[c]:-0}"
echo "remainder args: =$@="

for arg in "$@"
do
    do_work "$arg"
done
于 2013-07-08T18:22:45.633 回答
-1
OPTIND=1
while getopts "e:n:t:s:h" opt
do
    case $opt in
        e) echo "e OPTARG=${OPTARG} ";;
        n) echo "n OPTARG=${OPTARG} ";;
        t) echo "t OPTARG=${OPTARG} ";;
        s) echo "s OPTARG=${OPTARG} ";;
        h) echo "h OPTARG=${OPTARG} ";;
    esac
done
于 2013-07-08T18:20:48.763 回答