Shell

If / else statements on bash script

bash An overview of if/else statements in Bash scripts and comparison conditions Bash provides the following forms of if/else statements:

  1. Using if for a basic comparison

    if [ condition ]
    then
    ...
    fi
  2. Using if and else for comparisons

    if [ condition ]
    then
    ...
    else
    ...
    fi
  3. Using if, elif (else if), and else for comparisons

    if [ condition ]
    then
    ...
    elif [ condition ]
    then
    ...
    else
    ...
    fi

Conditions can test many things. The available comparisons are summarized below.

String comparison operations

String ComparisonDescription
Str1 == Str2Returns true if the strings are equal
Str1 != Str2Returns true if the strings are not equal
-n Str1Returns true if the string is not null
-z Str1Returns true if the string is null

Numeric comparison operations

Numeric ComparisonDescription
expr1 -eq expr2Returns true if the expressions are equal
expr1-ne expr2Returns true if the expressions are not equal
expr1 -gt expr2Returns true if expr1 is greater than expr2
expr1 -ge expr2Returns true if expr1 is greater than or equal to expr2
expr1 -lt expr2Returns true if expr1 is less than expr2
expr1 -le expr2Returns true if expr1 is less than or equal to expr2
expr1 -a expr2True if both expr1 and expr2 are true.
expr1 -o expr2True if either expr1 or expr2 is true.
! expr1Negates the result of the expression

File test operations

File ConditionalsDescription
-d dirTrue if the file is a directory
-e file -a fileTrue if the file exists (note that this is not particularly portable, thus -f is generally used)
-f fileTrue if the provided string is a file
-g fileTrue if the group id is set on a file
-k fileTrue if file exists and “sticky” bit is set
-r fileTrue if the file is readable
-s fileTrue if the file has a non-zero size (size greater than zero)
-b fileTrue if file exists and is a block special file
-c fileTrue if file exists and is a character special file
-p fileTrue if file exists and is a named pipe (FIFO)
-t [fd]True if file descriptor fd is open and refers to a terminal. If fd is omitted, it defaults to 1 (standard output).
-u fileTrue if the user id is set on a file
-w fileTrue if the file is writable
-x fileTrue if the file is an executable
-O fileTrue if file exists and is owned by the effective user id
-G fileTrue if file exists and is owned by the effective group id
-L fileTrue if file exists and is a symbolic link
-S fileTrue if file exists and is a socket.
-N fileTrue if file exists and has been modified since it was last read.
FILE1 -nt FILE2True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.
FILE1 -ot FILE2True if FILE1 is older than FILE2, or if FILE2 exists and FILE1 does not.
FILE1 -ef FILE2True if FILE1 and FILE2 refer to the same device and inode numbers.
EOF.← Back to articles