【问题标题】:How to do named command line arguments in Bash Scripting better way?如何在 Bash Scripting 中以更好的方式执行命名命令行参数?
【发布时间】:2018-11-11 00:32:55
【问题描述】:

这是我的示例 Bash 脚本 example.sh

 #!/bin/bash

 # Reading arguments and mapping to respective variables
 while [ $# -gt 0 ]; do
   if [[ $1 == *"--"* ]]; then
        v="${1/--/}"
        declare $v
   fi
  shift
 done

 # Printing command line arguments through the mapped variables
 echo ${arg1}
 echo ${arg2}

现在,如果在终端中我按如下方式运行 bash 脚本:

$ bash ./example.sh "--arg1=value1" "--arg2=value2"

我得到正确的输出,例如:

value1
value2

完美!这意味着我可以使用 bash 脚本中的变量 ${arg1} 和 ${arg2} 来使用传递给参数 --arg1 和 --arg2 的值。

我现在对这个解决方案很满意,因为它符合我的目的,但是,任何人都可以提出更好的解决方案来在 bash 脚本中使用命名命令行参数?

【问题讨论】:

    标签: bash command arguments line named


    【解决方案1】:

    你可以只使用环境变量:

    #!/bin/bash
    
    echo "$arg1"
    echo "$arg2"
    

    无需解析。从命令行:

    $ arg1=foo arg2=bar ./example.sh
    foo
    bar
    

    甚至还有一个 shell 选项可以让您将分配放在任何地方,而不仅仅是在命令之前:

    $ set -k
    $ ./example.sh arg1=hello arg2=world
    hello
    world
    

    【讨论】:

    • “set -k”是干什么用的?我喜欢那个解决方案,但是在触发 bash 脚本传递参数之前必须这样做。有什么可以自动处理的吗?
    • 不,因为它是 调用 shell 需要支持它。
    猜你喜欢
    • 2022-07-26
    • 2018-06-12
    • 2011-06-17
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多