bash-将可选参数传递给脚本-parametername + string_value

我使用接受参数的脚本。参数是可选的,可以以任何顺序出现。

#!/bin/bash
# script name: test.sh
for var in "$@"
do
    if [ ! -z "$var" ]   && ([ $var = "--example" ] || [ $var = "-e" ]); then
        echo "example"
    elif [ ! -z "$var" ]   && ([ $var = "--project" ] || [ $var = "-p" ]); then
        echo "project with string xxxxxxx"
    fi
done

在这个简单的示例中,您可以将其命名为以下示例(某些示例):

# this will echo example
./test.sh --example 
# this will echo project with string xxxxxxx
./test.sh --project
# this will echo both example and project with string xxxxxxx
./test.sh --example --project

现在,我要实现的是我可以做类似的事情(警告,这是pseuco代码):

#!/bin/bash
# script name: test.sh
for var in "$@"
do
    if [ ! -z "$var" ]   && ([ $var = "--example" ] || [ $var = "-e" ]); then
        echo "example"
    elif [ ! -z "$var" ]   && ([ $var = "--project" ] || [ $var = "-p" ]); then
        echo "project with string $VAR_VALUE"
    fi
done



# this will echo example
./test.sh --example 
# this will echo project with string myproject1
./test.sh --project="myproject1" 
# this will echo both example and project with string myproject2
./test.sh --example --project="myproject2"

有人可以帮我重写它吗,这样可以正常工作吗?

zyp0374 回答:bash-将可选参数传递给脚本-parametername + string_value

解析参数列表有两种可能的途径

  1. 构建自定义选项解析器
  2. 使用getopt,使用“长选项”

第一种方法相对简单(目前)。使用case而非if来处理变体:

last_arg=
for arg in "$@"
do
    if [ "$last_arg" = "-p" ] ; then
        VAR_VALUE=$arg ;
        last_arg=
        echo "project with string $VAR_VALUE"
        continue
    fi
    case "$arg" in
        -e | --example)
            echo "example" ;;
        -p)
            last_arg=$arg ;;
        --project=*)
            VAR_VALUE=${arg#*=}
            echo "project with string $VAR_VALUE" ;;
        *) ERROR-MESSAGE ;;
    esac
done
exit

更好的方法是利用现有代码。特别是getopt,它可以处理长选项:

#! /bin/bash
if T=$(getopt -o ep: --long 'example,project:' -n ${0#*/} -- "$@") ; then
        eval set -- "$T"
else
        exit $?
fi
while [ "$#" -gt 0 ] ; do
        case "$1" in
                -e | --example)
                        echo "example"
                        ;;
                -p | --project)
                        shift
                        VAR_VALUE=$1
                        echo "project with string $VAR_VALUE"
                        ;;
                --)
                        break
                        ;;
                *) echo "ERROR:$1" ;;
        esac
        shift
done
,

使用getopt。它处理长和短选项,同时允许--long value--long=value,将-abc分解为-a -b -c,理解--以结束选项解析,等等。

#!/bin/bash

args=$(getopt -o ep: -l example,project: -n "$0" -- "$@") || exit
eval set -- "$args"

while [[ $1 != '--' ]]; do
    case "$1" in
        -e|--example) echo "example";      shift 1;;
        -p|--project) echo "project = $2"; shift 2;;

        # shouldn't happen unless we're missing a case
        *) echo "unhandled option: $1" >&2; exit 1;;
    esac
done
shift  # skip '--'

echo "remaining non-option arguments: $@"
本文链接:https://www.f2er.com/3110346.html

大家都在问