在bash中添加和更改参数

问题描述 投票:0回答:1

有没有办法获取参数,无论它是什么,并将其更改为更具体的输出。

我试图找到一种方法,我可以将M26 (or M27, M28, L26, L27....)更改为M0000026.00,以便稍后在脚本中我可以调用参数的新形式

我知道我可以这样做:

./test.sh M26

if [ "$1" = M26 ]

   then

   set -- "M0000026.00" "${@:1}"

fi

some function在文件串$1中调用/..../.../.../$1/.../..

但我正在寻找更通用的方法,所以我不必为每个3字符参数输入所有可能的if语句

bash parameters editing
1个回答
0
投票

如果您的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 "$1" exists as a key in map, then use the mapped value.
   # Otherwise, just use "$1"
   args+=( "${map["$1"]-$1}" )
   shift
done

# At this point, you can either just use the args array directly and ignore
# $1, $2, etc. 
# Or you can use set to reassign $1, $2, etc from args, like so:
set -- "${args[@]}"

此外,您不必像我一样在一行上声明map。为了可维护性(特别是如果你有很多映射),你可以这样做:

declare -A map=()
map["M26"]="M0000026.00"
map["M27"]="whatever"
...
map["Z99"]="foo bar"
© www.soinside.com 2019 - 2024. All rights reserved.