19

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?

3 Answers 3

24

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).

Sign up to request clarification or add additional context in comments.

Comments

12

I would suggest using an array

#!/bin/bash

array=("" 1 2 "")

for i in "${array[@]}";do
    echo $i
done

2 Comments

Note: the quotes around "${array[@]}" are important, otherwise it won't work.
Explanation for the previous comment.
0

I was constructing an array containing another bash variable, variablea, that happened to be empty. It is important in this case to initialize such an array by quoting the bash variable.

VARS=( "$variablea" )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.