As an example:
List="A B C D"
for I in $List
do OUT=$OUT" -$I"
doneWhen 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.
2 Answers
Use conditional parameter expansion:
List="A B C D"
for I in $List
do OUT=${OUT:+$OUT }-$I
doneThe 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
doneDepending 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")
doneThen 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# }