在 bash 中添加和更改参数
adding to and changing a parameter in bash
有没有办法不管参数是什么,并将其更改为更具体的输出。
我正在尝试找到一种可以将 M26 (or M27, M28, L26, L27....)
更改为 M0000026.00
的方法,以便稍后在脚本中调用参数的新形式
我知道我可以做类似的事情:
./test.sh M26
if [ "" = M26 ]
then
set -- "M0000026.00" "${@:1}"
fi
some function
在文件字符串 /..../.../...//.../..
中调用 </code>
<p>但我正在寻找更通用的方法,这样我就不必为我拥有的每个 3 个字符参数输入所有可能的 <code>if
语句
如果您的 bash
版本支持关联数组,您可以这样做:
# Declare an associative array to contain your argument mappings
declare -A map=( [M26]="M0000026.00" [M27]="whatever" ["param with spaces"]="foo" )
# Declare a regular array to hold your remapped args
args=()
# Loop through the shell parameters and remap them into args()
while (( $# )); do
# If "" exists as a key in map, then use the mapped value.
# Otherwise, just use ""
args+=( "${map[""]-}" )
shift
done
# At this point, you can either just use the args array directly and ignore
# , , etc.
# Or you can use set to reassign , , etc from args, like so:
set -- "${args[@]}"
此外,您不必像我一样在一行中声明 map
。为了可维护性(特别是如果你有很多映射),你可以这样做:
declare -A map=()
map["M26"]="M0000026.00"
map["M27"]="whatever"
...
map["Z99"]="foo bar"
有没有办法不管参数是什么,并将其更改为更具体的输出。
我正在尝试找到一种可以将 M26 (or M27, M28, L26, L27....)
更改为 M0000026.00
的方法,以便稍后在脚本中调用参数的新形式
我知道我可以做类似的事情:
./test.sh M26
if [ "" = M26 ]
then
set -- "M0000026.00" "${@:1}"
fi
some function
在文件字符串 /..../.../...//.../..
</code>
<p>但我正在寻找更通用的方法,这样我就不必为我拥有的每个 3 个字符参数输入所有可能的 <code>if
语句
如果您的 bash
版本支持关联数组,您可以这样做:
# Declare an associative array to contain your argument mappings
declare -A map=( [M26]="M0000026.00" [M27]="whatever" ["param with spaces"]="foo" )
# Declare a regular array to hold your remapped args
args=()
# Loop through the shell parameters and remap them into args()
while (( $# )); do
# If "" exists as a key in map, then use the mapped value.
# Otherwise, just use ""
args+=( "${map[""]-}" )
shift
done
# At this point, you can either just use the args array directly and ignore
# , , etc.
# Or you can use set to reassign , , etc from args, like so:
set -- "${args[@]}"
此外,您不必像我一样在一行中声明 map
。为了可维护性(特别是如果你有很多映射),你可以这样做:
declare -A map=()
map["M26"]="M0000026.00"
map["M27"]="whatever"
...
map["Z99"]="foo bar"