【问题标题】:Pass a list of variables to a Bash script将变量列表传递给 Bash 脚本
【发布时间】:2010-12-13 12:34:59
【问题描述】:

我需要能够读取遵循某些参数的变量列表(例如,类似于 mysqldump --databases db1 db2 db3)

基本上应该像这样调用脚本:

./charge.sh --notify --target aig wfc msft --amount 1bln

在脚本本身中,我需要将“aig wfc msft”分配给单个变量或从中创建一个数组。

这样做的好方法是什么?

【问题讨论】:

    标签: bash command-line scripting


    【解决方案1】:

    我经常发现 shift 语句在这种情况下非常有用。在 while 循环中,您可以测试 case 语句中的预期选项,在每次迭代期间使用 shift 弹出参数 0,直到到达末尾或第一个位置参数。

    当您在循环中到达 --target 参数时,您可以使用 shift 将其从参数列表中弹出,然后在循环中,将每个参数附加到列表中(在此case $TARGET_LIST) 并移位,直到到达参数列表的末尾或下一个选项(当 '$1' 以 '-' 开头时)。

    NOTIFY=0
    AMOUNT=''
    TARGET_LIST=''
    
    while :; do
        case "$1" in
            -h|--help)
                echo "$HELP"
                exit 0
                ;;
            --notify)
                NOTIFY=1
                shift
                ;;
            --amount)
                shift; AMOUNT="$1"; shift
                ;;
            --target)
                shift
                while ! echo "$1" | egrep '^-' > /dev/null 2>&1 && [ ! -z "$1" ]; do
                    TARGET_LIST="$TARGET_LIST $1"
                    shift
                done
                ;;
            -*)
                # Unexpected option
                echo $USAGE
                exit 2
                ;;
            *)
                break
                ;;
        esac
    done
    

    【讨论】:

      【解决方案2】:

      如果你可以像这样调用脚本(注意引号):

      ./charge.sh --notify --target "aig wfc msft" --amount 1bln

      您可以将“aig wcf msft”分配给单个变量。

      如果您无法更改调用脚本的方式,并且如果您可以保证 --target 选项参数始终后跟另一个选项或其他分隔符,您可以获取它们之间的参数并将它们存储在一个变量中。

      var=$(echo $* | sed -e 's/.*--target\(.*\)--.*/\1/')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-13
        • 1970-01-01
        • 1970-01-01
        • 2012-03-10
        • 2020-05-20
        • 2020-05-24
        相关资源
        最近更新 更多