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
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.
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 -a services=([0]="webserver" [1]="wistudio") # it is an array!
and not
declare -- services="webserver wistudio" # it is a plain string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.