14

I would like to know whether it is possible to have more than two statements in an if statement when you are writing a shell script?

username1="BOSS1"
username2="BOSS2"
password1="1234"
password2="4321"

if(($username == $username1)) && (($password == password1)) || 
  (($username == $username2)) && (($password == password2)) ; then

This does NOT work. But is there a way to make it work?

Thanks!

user3604466
  • 141
  • 1
  • 1
  • 3

2 Answers2

44

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi
nettux
  • 5,270
  • 2
  • 23
  • 33
13

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 4
    Also be careful about whitespace. All those spaces need to be there! It must be `if [[ $username` and not `if[[$username`. Correct whitespace is critical in shell scripts, unlike most other programming languages. – John Kugelman May 08 '14 at 14:05