Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 375
Tuetschek Avatar asked Oct 14 '15 13:10

Tuetschek


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do I loop through a string in bash?

Create a bash file named 'for_list1.sh' and add the following script. A string value with spaces is used within for loop. By default, string value is separated by space. For loop will split the string into words and print each word by adding a newline.

Is empty string bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

What does %% mean in bash?

The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching. Follow this answer to receive notifications.


1 Answers

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

like image 121
Etan Reisner Avatar answered Sep 19 '22 10:09

Etan Reisner