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 a nonempty value, then it expands to that value 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")
The regex ^|
matches either the beginning of the string or a space; the replacement &-
means "whatever the regex matched" (the empty string at the start, or a space) followed by a minus sign.