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?
$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.
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.
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"
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With