Conditional Statements in Shell Programming

LinuxLinuxBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to use conditional statements in shell programming to make logical decisions. We will cover the basic syntax of if-else statements, as well as how to use numeric and string comparisons to evaluate conditions. You will also practice writing code that demonstrates various types of comparisons and logical combinations.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/InputandOutputRedirectionGroup(["`Input and Output Redirection`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) shell/ControlFlowGroup -.-> shell/if_else("`If-Else Statements`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/InputandOutputRedirectionGroup -.-> linux/pipeline("`Data Piping`") linux/BasicSystemCommandsGroup -.-> linux/logical("`Logic Operations`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/ControlFlowGroup -.-> shell/for_loops("`For Loops`") shell/ControlFlowGroup -.-> shell/cond_expr("`Conditional Expressions`") shell/AdvancedScriptingConceptsGroup -.-> shell/arith_expansion("`Arithmetic Expansion`") shell/AdvancedScriptingConceptsGroup -.-> shell/cmd_substitution("`Command Substitution`") shell/AdvancedScriptingConceptsGroup -.-> shell/subshells("`Subshells and Command Groups`") shell/SystemInteractionandConfigurationGroup -.-> shell/globbing_expansion("`Globbing and Pathname Expansion`") subgraph Lab Skills shell/if_else -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} linux/echo -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} linux/pipeline -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} linux/logical -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} linux/cd -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} linux/chmod -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/shebang -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/comments -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/quoting -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/variables_decl -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/variables_usage -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/for_loops -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/cond_expr -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/arith_expansion -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/cmd_substitution -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/subshells -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} shell/globbing_expansion -.-> lab-153899{{"`Conditional Statements in Shell Programming`"}} end

Basic if Statement

The basic syntax of an if statement in shell programming is as follows:

if [ expression ]; then
  ## code to execute if the expression is true
fi

Let's start by creating a simple if statement that checks if a variable called NAME is equal to "John".

#!/bin/bash
NAME="John"
if [ "$NAME" = "John" ]; then
  echo "True - my name is indeed John"
fi

Create a file called ~/project/if.sh and paste the above code into it. Then, run the script:

cd ~/project
chmod +x if.sh
./if.sh
True - my name is indeed John

if-else Statement

You can expand the if statement to include an else clause, which allows you to specify code to execute when the expression is false.

Update the if.sh script to include an else clause that prints a message when the NAME variable is not equal to "John":

#!/bin/bash
NAME="Bill"
if [ "$NAME" = "John" ]; then
  echo "True - my name is indeed John"
else
  echo "False"
  echo "You must mistaken me for $NAME"
fi

The above script will print "False" and "You must mistaken me for Bill" because the expression is false.

if-elif-else Statement

You can further expand the if statement to include multiple elif clauses, which allow you to specify additional expressions to evaluate if the previous ones are false.

Update the if.sh script to include an elif clause that checks if the NAME variable is equal to "George":

#!/bin/bash
NAME="George"
if [ "$NAME" = "John" ]; then
  echo "John Lennon"
elif [ "$NAME" = "George" ]; then
  echo "George Harrison"
else
  echo "This leaves us with Paul and Ringo"
fi

The above script will print "George Harrison" because the expression is true.

Numeric Comparisons

You can use numeric comparisons to evaluate conditions in shell scripts. Here are some examples of numeric comparisons:

  • -lt: less than
  • -gt: greater than
  • -le: less than or equal to
  • -ge: greater than or equal to
  • -eq: equal to
  • -ne: not equal to

Update the if.sh script to include a numeric comparison that checks if the NUMBER variable is equal to the APPLES variable:

#!/bin/bash
NUMBER=10
APPLES=10
KING=GEORGE

if [ $NUMBER -gt 15 ]; then
  echo 1
fi
if [ $NUMBER -eq $APPLES ]; then
  echo 2
fi

The above script will print "2" because the expression is true.

String Comparisons

You can also use string comparisons to evaluate conditions. Here are some examples of string comparisons:

  • "=": equal to
  • "==": equal to
  • "!=": not equal to
  • "-z": empty string

Update the if.sh script to include a string comparison that checks if the KING variable is equal to "LUIS":

#!/bin/bash
NUMBER=10
APPLES=12
KING=LUIS

if [[ ($APPLES -eq 12) || ("$KING" = "LUIS") ]]; then
  echo 3
fi

The above script will print "3" because the expression is true.

Logic Combinations

You can combine multiple conditions using logical operators like && (logical AND) and || (logical OR).

Update the if.sh script to include a logical OR operator that checks if the sum of the NUMBER and APPLES variables is less than or equal to 32:

#!/bin/bash
NUMBER=10
APPLES=12
KING=GEORGE

if [[ $(($NUMBER + $APPLES)) -le 32 ]]; then
  echo 4
fi

The above script will print "4" because the expression is true.

Summary

Congratulations! You have completed the Shell Programming Lab on Decision Making. You have learned how to use if-else and if-elif-else statements to make logical decisions in shell scripts. You have also practiced using numeric and string comparisons, as well as logical combinations to evaluate conditions. Keep practicing to further enhance your shell programming skills.

Other Linux Tutorials you may like