Logical AND

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to search

← Conditional executionHomeLogical OR →

Logical and (&&) is boolean operator. It can execute commands or shell functions based on the exit status of another command.


command1 && command2


First_command && Second_command

command2 is executed if, and only if, command1 returns an exit status of zero (true). In other words, run command1 and if it is successfull, then run command2.


Type the following at a shell prompt:

rm /tmp/filename && echo "File deleted."

The echo command will only run if the rm command exits successfully with a status of zero. If file is deleted successfully the rm command set the exit stats to zero and echo command get executed.

Lookup a username in /etc/passwd file

grep "^vivek" /etc/passwd && echo "Vivek found in /etc/passwd"

Exit if a directory /tmp/foo does not exist

test ! -d /tmp/foo && { read -p "Directory /tmp/foo not found. Hit [Enter] to exit..." enter; exit 1; }

External links

← Conditional executionHomeLogical OR →