stringbashfor-loop

How to pass empty string to bash for loop


I want to pass an empty string as one of the values to a bash for-loop – like this:

for var in "" A B C; do
    ...
done

This works. However, I would like to store the possible values in a variable, like this:

VARS="" A B C
for var in $VARS; do
    ...

Here, the empty string is ignored (or all values are concatenated if I use for var in "$VARS"). Is there an easy way to solve this?


Solution

  • You can't. Don't do that. Use an array.

    This is a version of Bash FAQ 050.

    VARS=("" A B C)
    for var in "${VARS[@]}"; do
        : ...
    done
    

    And you almost never want to use an unquoted variable (like for var in $VARS).