≡ Menu

6 Bash Conditional Expression Examples ( -e, -eq, -z, !=, [, [[ ..)

Bash expression is the combination of operators, features, or values used to form a bash conditional statement. Conditional expression could be binary or unary expression which involves numeric, string or any commands whose return status is zero when success.

There are several conditional expressions that could be used to test with the files. Following are few conditional expressions that are helpful.

  • [ -e filepath ] Returns true if file exists.
  • [ -x filepath ] Returns true if file exists and executable.
  • [ -S filepath ] Returns true if file exists and its a socket file.
  • [ expr1 -a expr2 ] Returns true if both the expression is true.
  • [ expr1 -o expr2 ] Returns true if either of the expression1 or 2 is true.

For more conditional expression to check the files, strings and numerics please refer the bash man page.

Bash Example 1. Check File Existence

The following Bash shell script code-snippet gets the filename with its absolute path, and checks if the file exists or not and it throws the appropriate information.

$ cat exist.sh
#! /bin/bash
if [ -e $file ]
	echo -e "File $file exists"
	echo -e "File $file doesnt exists"

$ ./exist.sh /usr/bin/boot.ini
File /usr/bin/boot.ini exists

Refer to our previous article to understand the various bash if statement types.

Bash Example 2. Compare Numbers

The below script reads two integer numbers from user, and checks if both the numbers are equal or greater or lesser than each other.

$ cat numbers.sh
echo "Please enter first number"
read first
echo "Please enter second number"
read second

if [ $first -eq 0 ] && [ $second -eq 0 ]
	echo "Num1 and Num2 are zero"
elif [ $first -eq $second ]
	echo "Both Values are equal"
elif [ $first -gt $second ]
	echo "$first is greater than $second"
	echo "$first is lesser than $second"

$ ./numbers.sh
Please enter first number
Please enter second number
Both Values are equal

$ ./numbers.sh
Please enter first number
Please enter second number
3 is lesser than 12

If you are new to bash scripting, refer to our Bash Introduction tutorial.

Bash Example 3. Basic Arithmetic Calculator

This examples reads input, which is a type of arithmetic operation wants to perform on bash variables (inp1 and inp2). The arithmetic operation could be addition, subtraction or multiplication..

$ cat calculator.sh
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo -n "Please choose a word [1,2 or 3]? "
read oper

if [ $oper -eq 1 ]
	echo "Addition Result " $(($inp1 + $inp2))
	if [ $oper -eq 2 ]
		echo "Subtraction Result " $(($inp1 - $inp2))
		if [ $oper -eq 3 ]
			echo "Multiplication Result " $(($inp1 * $inp2))
			echo "Invalid input"

$ ./calculator.sh
1. Addition
2. Subtraction
3. Multiplication
Please choose a word [1,2 or 3]? 4
Invalid input

Knowing how to use the bash special parameters ( $*, $@, $#, $$, $!, $?, $-, $_ ) will make your scripting life easy.

Bash Example 4. Read and Ping IP address

The following script is used to read the IP address and check whether the IP address is reachable, and prints the appropriate message.

$ cat ipaddr.sh
echo "Enter the Ipaddress"
read ip

if [ ! -z $ip ]
	ping -c 1 $ip
	if [ $? -eq 0 ] ; then
		echo "Machine is giving ping response"
		echo "Machine is not pinging"
	echo "IP Address is empty"

$ ./ipaddr.sh
Enter the Ipaddress

Pinging with 32 bytes of data:

Reply from bytes=32 time<1ms TTL=128

Ping statistics for
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms
Machine is giving ping response

In this example, -z returns true if ipaddress is zero length, When the condition is preceded by ! (negate) operator, if expression is false, it enters into if part and executes. So when the IP address is not null, it enters and checks whether the ip address is reachable.

Bash Example 5. Installer Script

Installer script of most of the packages will not allow to execute those as a root user. Script checks the user who is executing and throws the error.

The following script, allows you to execute the oracle installer script only if the user who is executing is non root.

$ cat preinstaller.sh
if [ `whoami` != 'root' ]; then
	echo "Executing the installer script"
	echo "Root is not allowed to execute the installer script"

Executing the script as a root user,
# ./preinstaller.sh
Root is not allowed to execute the installer script

In this example the output of the command whoami is compared with the word “root”. For string comparison ==, !=, < and should be used and for numeric comparison eq, ne,lt and gt should be used.

Bash Example 6. Enhanced brackets

In all the above examples, we used only single brackets to enclose the conditional expression, but bash allows double brackets which serves as an enhanced version of the single-bracket syntax.

$ cat enhanced.sh
echo "Enter the string"
read str
if [[ $str == *condition* ]]
	echo "String "$str has the word \"condition\"

$ ./enhanced.sh
Enter the string
String conditionalstatement has the word "condition"
  • [ is a synonym for test command. Even if it is built in to the shell it creates a new process.
  • [[ is a new improved version of it, which is a keyword, not a program.
  • [[ is understood by Korn and Bash.
  • In the above example, if the variable $str contains the phrase “condition” anywhere, the condition is true.
  • This is the shell globbing feature, which will be supported only when you use [[ (double brackets) and therefore many arguments need not be quoted.
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Slavko June 21, 2010, 7:36 am

    [ ! -z “$ip” ] [ -n “$ip” ] [ “$ip” ]


  • yoander June 21, 2010, 8:10 am

    In Example 6 you can use this alternative:
    echo “Enter the string”
    read str
    [[ $str == *condition* ]] && echo “String “$str has the word \”condition\”

  • dj June 21, 2010, 11:45 am

    Don’t forget ((expression))

  • bruce banner June 21, 2010, 4:29 pm


    /sbin/ifconfig eth0 | grep “inet addr” | cut -d: -f2 | cut -d’ ‘ -f1

  • fs June 28, 2010, 4:34 pm

    [[ $str == .*condition.* ]] && …
    [[ $str =~ condition ]] && …

  • Remy September 10, 2010, 3:11 pm

    Always use double quotes in string comparison to avoid errors if white space in the variable value.

    “$str” == “condition”

    Bash Example 1
    if a filename has white space in it then the variable holding the filename should be in double quotes -> “”.
    [[ -f “$file” ]] && echo Found || echo ‘Not found’

    Bash Example 2

    Better to validate before we compare.

    if [[ $(echo “$first” | egrep -q “^[0-9]{1,}$”; echo $?) -ne 0 ]]; then
    echo “$first” is not a number
    exit 1

    if [[ $(echo “$second” | egrep -q “^[0-9]{1,}$”; echo $?) -ne 0 ]]; then
    echo “$second” is not a number
    exit 1

  • thiripura August 26, 2012, 11:38 am

    pls source code for shell program for the following –
    i. Passwd, ii ipconfig, iii ping