Reputation: 245
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
Upvotes: 5
Views: 3636
Reputation: 42999
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
Upvotes: 8