0

我的 Bash-Script 应该接受参数和选项。此外,参数和选项应该传递给另一个脚本。

我解决的第二部分:

for argument in "$@"; do
    options $argument
done

another_script $ox $arguments

function options {
  case "$1" in
    -x) selection=1
    -y) selection=2
    -h|--help) help_message;;
    -*) ox="$ox $1";;
    *) arguments="$arguments $1";;
  esac
}

现在我不知道如何实现一个参数“-t”,用户可以在其中指定一些文本

它应该看起来像这样:

function options {
      case "$1" in
        -t) user_text=[ENTERED TEXT FOR OPTION T]
        -x) selection=1
        -y) selection=2
        -h|--help) help_message;;
        -*) ox="$ox $1";;
        *) arguments="$arguments $1";;
      esac
    }
4

3 回答 3

3

你可以用getopts这个

while getopts :t:xyh opt; do
    case "$opt" in
    t) user_text=$OPTARG ;;
    x) selection=1 ;;
    y) selection=2 ;;
    h) help_message ;;
    \?) commands="$commands $OPTARG" ;;
    esac
done

shift $((OPTIND - 1))

剩下的论点在"$@"

于 2013-03-08T22:03:49.713 回答
2

Your problem is that when options can take arguments, it isn't sufficient to process the arguments word-by-word; 您需要比提供options功能更多的上下文。把循环放在里面options,像这样:

function options {
    while (( $# > 0 )); do
        case "$1" in
            -t) user_text=$2; shift; ;;
            -x) selection=1 ;;
            # ...
        esac
        shift
    done
}

然后调用options整个参数列表:

options "$@"

您可能还想查看getopts内置命令或getopt程序。

于 2013-03-08T22:01:45.393 回答
0

我会在 for 循环中执行 case 语句,以便我可以强制转换到第二个 next 参数。就像是:

while true
do
  case "$1" in
    -t) shift; user_text="$1";;
    -x) selection=1;;
...
  esac
  shift
done
于 2013-03-08T22:09:29.690 回答