1

I am trying to check for multiple variables and see if any of them is zero and I came up with the following:

if [[ -z $var1 ]] || [[ -z $var2 ]] || [[ -z $var3 ]] || [[ -z $var4 ]] || [[ -z $var5 ]] || [[ -z $var6 ]] || [[ -z $var7 ]] || [[ -z $var8 ]]; then
    echo GOOD
fi

This works, but is there any other neat alternative to this?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Newbie
  • 11
  • 3
  • 3
    These variables should probably be in an array, in which case you can easily loop over them. – that other guy Jan 10 '18 at 22:18
  • 3
    `if ! [[ $var1 && $var2 && $var3 && $var4 && $var5 ... ]]` – Charles Duffy Jan 10 '18 at 22:18
  • 2
    ...but what @thatotherguy said -- especially if these are *really* the same basename with a bunch of distinct numbers following. – Charles Duffy Jan 10 '18 at 22:19
  • BTW, it might be arguable that this is duplicative of [What's a concise way to check that environmental variables are set in a Unix shell script?](https://stackoverflow.com/questions/307503/whats-a-concise-way-to-check-that-environment-variables-are-set-in-a-unix-shell). – Charles Duffy Jan 10 '18 at 22:24
  • if ! [[ $var1 && $var2 && var3 ..... ]] always echos Good irrespective if any of the variables are empty or not. – Newbie Jan 10 '18 at 22:52
  • 1
    @Newbie, `$var3`, not `var3`. That version will always be true (before negation) because `var3` is always a non-empty string. – Charles Duffy Jan 11 '18 at 00:04
  • @Newbie, compare `var1=hello; var2=cruel; var3=world; { ! [[ $var1 && $var2 && $var3 ]]; } && echo Good` (which does nothing, like your original code in that case), to the same with `var3=` assigning an empty value (which emits `Good`). – Charles Duffy Jan 11 '18 at 00:07
  • @Newbie, btw, consider making use of `set -x` to enable trace-level logging -- it'll make it easy to catch that kind of error. – Charles Duffy Jan 11 '18 at 00:08
  • You could assign all your variables to an array and then just check the length – grail Jan 11 '18 at 05:14

1 Answers1

2

You could loose some brackets, like this:

if [[ -z $var1 || -z $var2 || -z $var3 || -z $var4 || -z $var5 || -z $var6 || -z $var7 || -z $var8 ]] ; then
    echo GOOD
fi

Or, as Charles Duffy suggested in the comments, you could invert the condition and end up with something even shorter:

if ! [[ $var1 && $var2 && $var3 && $var4 && $var5 && $var6 && $var7 && $var8 ]] ; then
    echo GOOD
fi
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
  • If it's bash golf you are playing, then using `(( ))` can omit the `$`: `if ! (( var1 && var2 && var3 ... ))` (since we are checking for zero). – cdarke Jan 10 '18 at 22:24
  • 1
    @cdarke, ...I worry that the OP said "zero" when they really meant "empty" or "zero bytes", though; random strings that look like variable names but aren't defined will read as zero in such a context. – Charles Duffy Jan 10 '18 at 22:28