5

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 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

4 Comments

Yes. It worked. can you please also tell me why it was wrong? because echo "$services[@]" would still give me the values correctly
I would also like to know if consider it as a string then how would the solution work? in my another script i have to pass the appended value to a executable, Which accept only string.
May be create another question with the details.
echo $* still has many potential problems due to word splitting and wildcard expansion. I'd recommend using services=("${@//\//}") to create the array, since it'll work correctly with pretty much anything in the arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.