Open In App

Conditional Statements | Shell Script

Last Updated : 27 Feb, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Conditional Statements: There are total 5 conditional statements which can be used in bash programming

  1. if statement
  2. if-else statement
  3. if..elif..else..fi statement (Else If ladder)
  4. if..then..else..if..then..fi..fi..(Nested if)
  5. switch statement

Their description with syntax is as follows:

if statement
This block will process if specified condition is true.
Syntax:

if [ expression ]
then
   statement
fi

if-else statement
If specified condition is not true in if part then else part will be execute.
Syntax

if [ expression ]
then
   statement1
else
   statement2
fi

if..elif..else..fi statement (Else If ladder)
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
Syntax

if [ expression1 ]
then
   statement1
   statement2
   .
   .
elif [ expression2 ]
then
   statement3
   statement4
   .
   .
else
   statement5
fi

if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies then it again checks another condition. In the syntax, if expression1 is false then it processes else part, and again expression2 will be check.
Syntax:

if [ expression1 ]
then
   statement1
   statement2
   .
else
   if [ expression2 ]
   then
      statement3
      .
   fi
fi

switch statement
case statement works as a switch statement if specified value match with the pattern then it will execute a block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.

Syntax:

case  in
   Pattern 1) Statement 1;;
   Pattern n) Statement n;;
esac

Example Programs

Example 1:
Implementing if statement




#Initializing two variables
a=10
b=20
  
#Check whether they are equal
if [ $a == $b ]
then
    echo "a is equal to b"
fi
  
#Check whether they are not equal
if [ $a != $b ]
then
    echo "a is not equal to b"
fi


Output

$bash -f main.sh
a is not equal to b

Example 2:
Implementing if.else statement




#Initializing two variables
a=20
b=20
  
if [ $a == $b ]
then
    #If they are equal then print this
    echo "a is equal to b"
else
    #else print this
    echo "a is not equal to b"
fi


Output

$bash -f main.sh
a is equal to b

Example 3:
Implementing switch statement




CARS="bmw"
  
#Pass the variable in string
case "$CARS" in
    #case 1
    "mercedes") echo "Headquarters - Affalterbach, Germany" ;;
      
    #case 2
    "audi") echo "Headquarters - Ingolstadt, Germany" ;;
      
    #case 3
    "bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;;
esac


Output

$bash -f main.sh
Headquarters - Chennai, Tamil Nadu, India.

Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts.



Next Article

Similar Reads

Shell Script to Show the Difference Between echo “$SHELL” and echo ‘$SHELL’
In shell scripting and Linux, the echo command is used to display text on the terminal or console. When used with the $SHELL variable, which contains the path of the current user's shell program, the output of the echo command can be different depending on whether the variable is enclosed in single or double quotes. echo "$SHELL" will expand the $S
4 min read
Bash Script - Difference between Bash Script and Shell Script
In computer programming, a script is defined as a sequence of instructions that is executed by another program. A shell is a command-line interpreter of Linux which provides an interface between the user and the kernel system and executes a sequence of instructions called commands. A shell is capable of running a script. A script that is passed to
3 min read
Shell Scripting - Difference between Korn Shell and Bash shell
Korn Shell: Korn Shell or KSH was developed by a person named David Korn, which attempts to integrate the features of other shells like C shell, Bourne Shell, etc. Korn Shell allows developers to generate and create new shell commands whenever it is required. Korn shell was developed a long year back as it is older than the BASH shell and it has fe
3 min read
Looping Statements | Shell Script
Looping Statements in Shell Scripting: There are total 3 looping statements that can be used in bash programming  Table of Content `while` statement in Shell Script in Linux`for` statement in Shell Script in Linux`until` statement in Shell Script in LinuxExamples of Looping StatementsTo alter the flow of loop statements, two commands are used they
10 min read
Shell Script to Demonstrate the Use of Shell Function Library
Shell Function Library is basically a collection of functions that can be accessed from anywhere in the development environment. It actually makes shell scripting a bit less tedious and repetitive. By creating a shell script with some functions defined in it, we can then access and call those functions from other files or scripts. It helps in avoid
3 min read
How to write a shell script that starts tmux session, and then runs a ruby script
Scripts are important for streamlining workflows and automating tasks. One such way to streamline workflow is by using Tmux [Terminal Multiplexer]. When used along with shell scripts we will be able to automatically commence a Tmux session and perform certain tasks. In this article, we shall see how to use a shell script that will automatically sta
4 min read
Shell Scripting - Restricted Shell
Shell is one of the most important and powerful tools available in GNU/Linux-based systems. One can control the entire system if used correctly, this exact feature makes the shell a double-edged sword. It can potentially harm the system if one executes a system command without knowing its underlying details and consequences. To prevent this we use
5 min read
Auto Logout in Linux Shell Using TMOUT Shell Variable
TMOUT is a Linux-Unix shell variable that provides the user security for their login session in the system. It provides the "Auto Logout Functionality" for the login shell in case of no activity for a specified time. Generally when the user leaves the Linux system idle (situation when a user doesn't perform any administrative task by running a comm
2 min read
Shell Scripting - Interactive and Non-Interactive Shell
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Default Shell Variable Value
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Korn Shell vs Bash Shell
Introduction : Korn Shell, also known as ksh, is a Unix shell that was developed by David Korn in the early 1980s. It was designed to be a more powerful and interactive shell than the Bourne Shell (sh), which was the standard Unix shell at the time. The Korn Shell has features such as command-line editing, job control, and shell scripting, making i
6 min read
How to protect Linux shell file using noclobber in bash shell?
Most Linux shells(bash, csh, ksh, tcsh) have a built-in file protection mechanism to prevent files from being overwritten accidentally. In this article, we will see how to prevent it by setting noclobber option. Clobbering Redirecting standard output to a file that already exists would overwrite the existing file content which will result in data l
2 min read
Shell Scripting - Shell Signals Values
Prerequisites: Processes, Bash Scripting, Shell Function Library Signals help the operating system to communicate with processes and vice-versa. Signals are also generated when processes don't function properly or try to access prohibited memory. Different signals are mapped to different numbers which are referred to as signal values. The Linux OS
6 min read
Introduction to Linux Shell and Shell Scripting
If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understanding shell scripting we have to get familiar with th
7 min read
Shell Scripting - Shell Variables
A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing
6 min read
Bash shell script to find sum of digits
Given a number Num, find the sum of digits of the number.Examples: Input : 444 Output : sum of digits of 444 is : 12 Input : 34 Output : sum of digits of 34 is : 7 Approach: 1. Divide the number into single digits 2. Find the sum of digits . C/C++ Code # !/bin/bash # Program to find sum # of digits # Static input of the # number Num=123 g=$Num # st
1 min read
String Operators | Shell Script
Pre-Requisite: Conditional Statement in Shell Script There are many operators in Shell Script some of them are discussed based on string. Equal operator (=): This operator is used to check whether two strings are equal. Syntax:Operands1 = Operand2Example: PHP Code #!/bin/sh str1="GeeksforGeeks"; str2="geeks"; if
2 min read
Implementing Directory Management using Shell Script
Directory management constitutes the functions dealing with organization and maintenance of various directories. Directories usually contain files of any type, but this may vary between file systems. The content of a directory does not affect the directory object itself. Some of the directory functions are: Navigation Absolute/ Relative Pathnames L
3 min read
Bash shell script to find out the largest value from given command line arguments
Write a shell script to find out the largest value from the given number of command-line arguments. Example: Special variables in bash: $@- All arguments. $#- Number of arguments. $0- Filename. $1, $2, $3, $4 ... - Specific arguments. Approach If the number of arguments is 0, end the program. If not zero, then Initialize a variable maxEle with firs
1 min read
Automated Recursive Encryption in a Directory Using Shell Script
This script would encrypt file provided as an argument or a directory and its constituent files and sub-directories recursively. It would be very useful for automating the encryption of multiple files in a directory all together. How it works? If no arguments are given, throw an error and exit the program. Read the password to use for encrypting th
3 min read
Multi-Line Comment in Shell Script
Comments are quite a crucial part of a program or a code-base. It helps in understanding the code, improves code-readability, and also helps in enhancing the structure of the program. We often write single-line comments in our programs as they are quite self-explanatory and require few words to describe the flow of the program or any message about
2 min read
Shell Script To Show All the Internal and External Links From a URL
To make hierarchy among the webpages or the information web developers use to connect them all is called webpage linking. There are two types of webpage linking: one is internal linking, and the other is external linking. Internal links are those which link a page available on the same website to produce a cycle on the site. At the same time, exter
4 min read
Difference Between Single and Double Quotes in Shell Script and Linux
Single quotes and double quotes are both functional in Linux while working with shell scripts or executing commands directly in the terminal but there is a difference between the way the bash shell interprets them. Single quotes: Enclosing characters in single quotation marks (') holds onto the literal value of each character within the quotes. In
3 min read
Shell Script to Join a String
There are different ways to concatenate strings in the shell. Some of them are listed below. String concatenation is used in shell scripting to make it much easier for the user to understand and use the program. Appending strings also allow the programmer to learn the working of concatenation on the shell. These are the ways for joining the string:
3 min read
Shell Script to Split a String
Shell Scripting or Shell Programming is just like any other programming language. A shell is a special program that provides an interface between the user and the operating system. In Linux/Unix the default shell used is bash and in windows, it is cmd(command prompt). We use the terminal to run a shell command. Shell scripts are saved with .sh file
3 min read
Shell Script to Display All Words of a File in Ascending Order
Here we will see a shell script that will arrange all the words from a file in ascending order, which comes in handy when we have many words that need to be sorted in ascending order. The script helps to analyze the data easily and represent it in a much more organized manner. Approach: Store the value of the file into a filename variable.Store the
2 min read
Shell Script to Concatenate Two Strings
String concatenation is the process of appending a string to the end of another string. This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other. The examples below show some shell scripts that can be used to concatenate strings. Example 1: In this example, we will concatenate two
3 min read
Shell Script To Show Names of All Sub-Directories Present in Current Directory
In this given program, we are required to write a shell script to print the list of all the sub-directories present in the current directory. Currently, when we are running this program, the terminal is opened at the root directory location and hence, we are getting a list of sub-directories present at the root level. Moreover, this script comes in
2 min read
Shell Script to List all Hidden Files in Current Directory
Here we are going to see how to write a script to list all hidden files in the current directory, But before starting we will see how to hide the file in the current directory. Hide Files in Linux: In Linux, the files which start with a period (.) sign are the hidden files. We will write a small script to hide the file by providing the name of the
2 min read
Shell Script to List All IP
In a layman's language, IP addresses can be thought of as house addresses. Just like we have a unique house address for each house, similarly, we have a unique IP address for each unique device on the network. An IP address is used to uniquely identify a device on an internet protocol network. Example of an IP address: 192.0.2.1/24 Here, 192.0.2.1
2 min read
Article Tags :
  翻译: