How do I concatenate strings from a list in a bash script?
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")
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# }