bash - 将参数分配给位置参数
问题描述
我正在调用具有大量参数的 shell 脚本,例如./train-rnn.sh 0 0 0 "63 512"
. 是否可以将每个参数分配给特定的位置参数?例如
./train-rnn.sh $1=0 $2=0 $4=0 $3="63 512"
解决方案
Bash 没有这样的机制,但你可以做点什么。
最好的方法是解析脚本中的命令行参数。在这种情况下,您可能希望通过允许表单选项来改善用户体验,option=argument
而不是让用户(和开发人员也一样!)记住 、 等的$1
含义$2
。
#! /usr/bin/env bash
declare -A opt
for arg; do
if [[ "$arg" =~ ^([^=]+)=(.*) ]]; then
opt["${BASH_REMATCH[1]}"]=${BASH_REMATCH[2]}
else
echo "Error: Arguments must be of the form option=..." >&2
exit 1
fi
done
# "${opt["abc"]}" is the value of option abc=...
# "${opt[@]}" is an unordered (!) list of all values
# "${!opt[@]}" is an unordered (!) list of all options
示例用法:
script.sh abc=... xyz=...
如果您真的想坚持位置参数,请使用
#! /usr/bin/env bash
param=()
for arg; do
if [[ "$arg" =~ ^\$([1-9][0-9]*)=(.*) ]]; then
param[BASH_REMATCH[1]]=${BASH_REMATCH[2]}
else
echo "Error: Arguments must be of the form $N=... with N>=1" >&2
exit 1
fi
done
if ! [[ "${#param[@]}" = 0 || " ${!param[*]}" == *" ${#param[@]}" ]]; then
echo "Error: To use $N+1 you have to set $N too" >&2
exit 1
fi
set -- "${param[@]}"
# rest of the script
# "$@" / $1,$2,... are now set accordingly
示例用法:
script.sh $1=... $3=... $2=...
如果您的脚本/程序无法修改,上述方法也可以用作包装器。为此,请替换set -- "${param[@]}"
为exec program "${param[@]}"
,然后使用wrapper.sh $1=... $3=... $2=...
.
推荐阅读
- google-cloud-platform - GCP SQL 实例在重启时卡住
- python - 如何从头开始实现 find() 函数(无库)
- javascript - 在 v-for 循环中的每 n 个项目之后插入项目
- google-chrome - 编辑另一个扩展的 chrome.storage.local?
- python - 如何在计算图中动态插入“MutableHashTable”?
- angular - Angular Service Worker 无法在 Firebase 存储上缓存图像,导致 504(网关超时)
- javascript - Draft.js 仅在列表上修改文本对齐样式?
- android - 在 Chrome Android 中全屏运行的 PWA 不支持显示模式:独立
- python - 在 __getattr__ 中使用 __dict__ 属性
- c - 当我尝试打印(复制的)字符串时,为什么会得到一些任意数字?