I am storing command line parameters in an array variable. (This is necessary for me). I wanted to prefix all the array values with a string passing through a variable.
我将命令行参数存储在数组变量中。(这对我来说是必要的)。我想用一个通过变量的字符串对所有数组值进行前缀。
PREFIX="rajiv"
services=$( echo $* | tr -d '/' )
echo "${services[@]/#/$PREFIX-}"
I am getting this output.
我得到了这个输出。
> ./script.sh webserver wistudio
rajiv-webserver wistudio
But I am expecting this output.
但我期望的是这个输出。
rajiv-webserver rajiv-wistudio
1 个解决方案
#1
2
Your array initialization is wrong. Change it to this:
数组初始化是错误的。改成这样的:
services=($(echo $* | tr -d '/'))
Without the outer ()
, services
would become a string and the parameter expansion "${services[@]/#/$PREFIX-}"
adds $PREFIX-
to your string.
如果没有外部(),服务就会变成字符串,而参数扩展“${services[@]/#/$前缀-}”会在字符串中增加$前缀。
In situations like this, declare -p
can be used to examine the contents of your variable. In this case, declare -p services
should show you:
在这种情况下,可以使用declare -p检查变量的内容。在此情况下,申报-p服务应显示:
declare -a services=([0]="webserver" [1]="wistudio") # it is an array!
and not
而不是
declare -- services="webserver wistudio" # it is a plain string
#1
2
Your array initialization is wrong. Change it to this:
数组初始化是错误的。改成这样的:
services=($(echo $* | tr -d '/'))
Without the outer ()
, services
would become a string and the parameter expansion "${services[@]/#/$PREFIX-}"
adds $PREFIX-
to your string.
如果没有外部(),服务就会变成字符串,而参数扩展“${services[@]/#/$前缀-}”会在字符串中增加$前缀。
In situations like this, declare -p
can be used to examine the contents of your variable. In this case, declare -p services
should show you:
在这种情况下,可以使用declare -p检查变量的内容。在此情况下,申报-p服务应显示:
declare -a services=([0]="webserver" [1]="wistudio") # it is an array!
and not
而不是
declare -- services="webserver wistudio" # it is a plain string