Logical AND

From Linux Shell Scripting Tutorial - A Beginner's handbook

Jump to: navigation, search
← Conditional execution Home Logical OR →

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

Contents

[edit] Syntax

command1 && command2

OR

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.

[edit] Example

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.

[edit] Lookup a username in /etc/passwd file

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

[edit] 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; }

[edit] External links

← Conditional execution Home Logical OR →
Personal tools
Create a book