GDr*_*oid 1 bash command arguments line named
这是我的示例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}
Run Code Online (Sandbox Code Playgroud)
现在,如果在终端中运行 bash 脚本,如下所示:
$ bash ./example.sh "--arg1=value1" "--arg2=value2"
Run Code Online (Sandbox Code Playgroud)
我得到正确的输出,例如:
value1
value2
Run Code Online (Sandbox Code Playgroud)
完美的!这意味着我能够使用 bash 脚本中的变量 ${arg1} 和 ${arg2} 来使用传递给参数 --arg1 和 --arg2 的值。
我现在对这个解决方案很满意,因为它符合我的目的,但是,任何人都可以建议任何更好的解决方案来在 bash 脚本中使用命名命令行参数吗?
您可以只使用环境变量:
#!/bin/bash
echo "$arg1"
echo "$arg2"
Run Code Online (Sandbox Code Playgroud)
无需解析。从命令行:
$ arg1=foo arg2=bar ./example.sh
foo
bar
Run Code Online (Sandbox Code Playgroud)
甚至还有一个 shell 选项可以让您将赋值放在任何地方,而不仅仅是在命令之前:
$ set -k
$ ./example.sh arg1=hello arg2=world
hello
world
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2828 次 |
| 最近记录: |