Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in if statement shell script [duplicate]

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!

like image 756
user3604466 Avatar asked May 08 '14 13:05

user3604466


People also ask

How do you represent multiple conditions in a shell if statement?

To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.

How do you write an if statement with multiple conditions?

When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)

What is $@ and $* in shell script?

• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.

What is $1 $2 in shell script?

Shell scripts have access to some "magic" variables from the environment: $0 - The name of the script. $1 - The first argument sent to the script. $2 - The second argument sent to the script.


2 Answers

if using /bin/sh you can use:

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

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi
like image 162
nettux Avatar answered Sep 30 '22 13:09

nettux


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

like image 40
chepner Avatar answered Sep 30 '22 15:09

chepner