4

Is it possible to put more than 1 condition in an if statement?

if  [ "$name" != "$blank" && "$age" == "$blank" ]; then

Is it possible? If not how am I supposed to do that?

Zac
  • 489
  • 3
  • 11
  • 17
  • also has an answer [here](http://stackoverflow.com/questions/16203088/multiple-conditions-if-statement-bash-script) – Aman Jan 11 '15 at 12:45

2 Answers2

9

With [ expression ] (POSIX Standard) syntax you can use the following:

if [ "$name" != "$blank" ] && [ "$age" = "$blank" ]; then
   echo true
fi

But in [[ expression ]] syntax you can use both conditions:

if [[ $name != "$blank" && $age == "$blank" ]]; then
   echo true!
fi

Two advantages of [[ over [:

  1. No word splitting or glob expansion will be done for [[, and therefore many arguments need not be quoted (with the exception of the right-hand side of == and !=, which is interpreted as a pattern if it isn't quoted).
  2. [[ easier to use and less error-prone.

Downside of [[: it is only supported in ksh, bash and zsh, not in plain Bourne/POSIX sh.

My reference and good page to comparing [[ and [: bash FAQ

Security implications of forgetting to quote a variable in bash/POSIX shells

Sepahrad Salour
  • 2,629
  • 3
  • 20
  • 27
  • @mikeserv, Thank for your attention. I edited my post. – Sepahrad Salour Jan 11 '15 at 13:01
  • You mention that [ is POSIX standard. It's worth pointing out that [[ isn't. But if you're using other BASH features anyway, then def. use [[, it's better. (e.g. the bash-completion project coding standards mandate use of [[ ]].) – Peter Cordes Jan 11 '15 at 13:28
4

Yet another possibility not mentioned by @SepahradSalour is to use -a operator:

if [ "$name" != "$blank" -a "$age" = "$blank" ]; then

BTW, be sure to quote properly all variables separately.

jimmij
  • 46,064
  • 19
  • 123
  • 136
  • 1
    [According to spec](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) *The XSI extensions specifying the -a and -o binary primaries and the '(' and ')' operators have been marked obsolescent. (Many expressions using them are ambiguously defined by the grammar depending on the specific expressions being evaluated.)* – mikeserv Jan 11 '15 at 12:53
  • @mikeserv Interesting, I didn't know that. – jimmij Jan 11 '15 at 12:56
  • I suggest you modify the answer to include the comment from @mikeserv – lrineau Jan 12 '15 at 13:49