9

As an example:

List="A B C D"
for I in $List
do
    OUT=$OUT" -$I"
done

When I run this the result is:

" -A -B -C -D"

but want it to be:

"-A -B -C -D"

How do I concatenate without the leading space?

This btw is an argument list to a script.

14

Use conditional parameter expansion:

List="A B C D"
for I in $List
do
    OUT=${OUT:+$OUT }-$I
done

The expression ${OUT:+$OUT } expands to nothing if OUT is not set or empty; if it is set to something, then it expands to that something followed by a space.

However, this sort of operation - treating a whitespace-separated string as a list - is fraught with possible problems: quoting, values that unexpectedly contain spaces themselves, etc. You would be better off using an array:

List=(A B C D)
for I in "${List[@]}"
do    
    OUT=${OUT:+$OUT }-$I
done

Depending on what you're doing with $OUT, it might make sense to make it an array as well:

List=(A B C D)
OUT=()
for I in "${List[@]}"; do
  OUT+=("-$I")
done

Then you would use "${OUT[@]}" to pass on the elements of the array to another command as separate arguments.

To go back to your original version, in this specific case you could also just use sed and skip the bash loop entirely:

OUT=$(sed -E 's/^| /&-/g' <<<"$List")
1

You can remove the leading space using a command after the for-loop, such as

OUT=${OUT# }

Leading to

List="A B C D"
for I in $List
do
    OUT=$OUT" -$I"
done
OUT=${OUT# }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.