if-else in Shell Scripts

How to use if-else in shell script

It is easy to see the syntax of a function and believe you know how to use it. But it is always a better choice to understand a function through examples because they help you understand the role that different aspects of a function play.

Here are some useful examples of if-else in shell scripts to give you a better idea of how to use this tool.

CommandDescription
&&Logical AND
$0Argument 0 i.e. the command that’s used to run the script
$1First argument (change number to access further arguments)
-eqEquality check
-neInequality check
-ltLess Than
-leLess Than or Equal
-gtGreater Than
-geGreater Than or Equal

1. Using if-else to check whether two numbers are equal

When trying to understand the working of a function like if-else in a shell script, it is good to start things simple. Here, we initialize two variables a and b, then use the if-else function to check if the two variables are equal. The bash script should look as follows for this task.

#!/bin/bash
m=1
n=2

if [ $n -eq $m ]
then
        echo "Both variables are the same"
else
        echo "Both variables are different"
fi

Output:

Both variables are different

2. Using if-else to compare two values

The more common use of if-else in shell scripts is for comparing two values. Comparing a variable against another variable or a fixed value helps is used in a variety of cases by all sorts of programmers.

For the sake of this example, we will be initializing two variables and using the if-else function to find the variable which is greater than the other.

#!/bin/bash
a=2
b=7
if [ $a -ge $b ]
then
  echo "The variable 'a' is greater than the variable 'b'."
else
  echo "The variable 'b' is greater than the variable 'a'."
fi

Output:

The variable 'b' is greater than the variable 'a'.

3. Using if-else to check whether a number is even

Sometimes we come across situations where we need to deal with and differentiate between even and odd numbers. This can be done with if-else in shell scripts if we take the help of the modulus operator.

The modulus operator divides a number with a divisor and returns the remainder.

As we know all even numbers are a multiple of 2, we can use the following shell script to check for us whether a number is even or odd.

#!/bin/bash
n=10
if [ $((n%2))==0 ]
then
  echo "The number is even."
else
  echo "The number is odd."
fi

Output:

The number is even

As you can see, we’ve enclosed a part of the condition within double brackets. That’s because we need the modulus operation to be performed before the condition is checked.

Also, enclosing in double brackets runs statements in C-style allowing you to process some C-style commands within bash scripts.

4. Using if-else as a simple password prompt

The if-else function is known for its versatility and range of application. In this example, we will use if-else in shell script to make the interface for a password prompt.

To do this, we will ask the user to enter the password and store it in the variable pass.

If it matches the pre-defined password, which is ‘password’ in this example, the user will get the output as -“The password is correct”.

Else, the shell script will tell the user that the password was incorrect and ask them to try again.

#!/bin/bash
echo "Enter password"
read pass
if [ $pass="password" ]
then
  echo "The password is correct."
else
  echo "The password is incorrect, try again."
fi

5. นับจำนวนไฟล์ว่าเท่ากับจำนวนที่กำหนดหรือไม่

#!/bin/bash
a=NUM_FILE=`find . -type f -print | wc -l`
b=4
if [ $a -eq $b ]
then
  echo "Exactly the same."
else
  echo "Wrong number"
fi

6. start, stop process

ถ้า process ไม่ได้รันอยู่ ให้ start process

#!/bin/bash

a=`ps -ef | grep PROCESS_NAME | wc -l`
b=1

if [ $a -gt $b ]
then
  echo "Found existing process"
else
  echo "Not found existing, START PROCESS_NAME"
  start.sh
fi

ถ้า process รันอยู่ ให้ stop process

#!/bin/bash

a=`ps -ef | grep PROCESS_NAME | wc -l`
b=1

if [ $a -gt $b ]
then
  echo "Found existing, STOP PROCESS_NAME "
  stop.sh
else
  echo "Process not found"
fi

คำสั่ง pgrep

ทดสอบบน Red Hat 7.7

The pgrep command allows a user to find process IDs in the running program in the system’s current state.

$ pgrep --version
pgrep from procps-ng 3.3.10
$ pgrep --help

Usage:
 pgrep [options] <pattern>

Options:
 -d, --delimiter <string>  specify output delimiter
 -l, --list-name           list PID and process name
 -a, --list-full           list PID and full command line
 -v, --inverse             negates the matching
 -w, --lightweight         list all TID
 -c, --count               count of matching processes
 -f, --full                use full process name to match
 -g, --pgroup <PGID,...>   match listed process group IDs
 -G, --group <GID,...>     match real group IDs
 -n, --newest              select most recently started
 -o, --oldest              select least recently started
 -P, --parent <PPID,...>   match only child processes of the given parent
 -s, --session <SID,...>   match session IDs
 -t, --terminal <tty,...>  match by controlling terminal
 -u, --euid <ID,...>       match by effective IDs
 -U, --uid <ID,...>        match by real IDs
 -x, --exact               match exactly with the command name
 -F, --pidfile <file>      read PIDs from file
 -L, --logpidfile          fail if PID file is not locked
 --ns <PID>                match the processes that belong to the same
                           namespace as <pid>
 --nslist <ns,...>         list which namespaces will be considered for
                           the --ns option.
                           Available namespaces: ipc, mnt, net, pid, user, uts

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see pgrep(1).

ตัวอย่าง

หา process ID ของ nginx

$ pgrep nginx
1085
1086

specify output delimiter ด้วย -d

$ pgrep -d: nginx
1085:1086

match exactly with the command name ด้วย -x

$ pgrep -x nginx
1085
1086

หา process ID จาก user name

$ pgrep -u jack