Friday, January 17, 2025
HomeTechHow to if/else statement in shell script

How to if/else statement in shell script

In a shell script, you can use the if/else statement to execute different blocks of code based on conditions. Here’s the general syntax for an if/else statement in a shell script:

Basic Syntax:

if [ condition ]
then
    # Code to run if condition is true
else
    # Code to run if condition is false
fi

Explanation:

  • if: Starts the conditional statement.
  • [ condition ]: The condition to be tested. This can be a comparison, file check, or other conditions.
  • then: Specifies the block of code to execute if the condition is true.
  • else: Specifies the block of code to execute if the condition is false.
  • fi: Closes the if/else statement (in reverse order of if).
See also  len() of a numpy array in python

Example 1: Simple if/else

#!/bin/bash

number=10

if [ $number -gt 5 ]
then
    echo "The number is greater than 5."
else
    echo "The number is less than or equal to 5."
fi

Explanation:

  • $number -gt 5: This condition checks if the variable number is greater than 5.
  • The script will print “The number is greater than 5.” because 10 is greater than 5.

Example 2: If/else with string comparison

#!/bin/bash

name="John"

if [ "$name" == "Alice" ]
then
    echo "Hello Alice!"
else
    echo "Hello, stranger!"
fi

Explanation:

  • "$name" == "Alice": Compares the string in name to "Alice".
  • Since name is “John”, the script will print “Hello, stranger!”.
See also  Introduction to Microsoft Azure A Cloud Computing Service

Example 3: If/else with multiple conditions

You can use elif (else if) to check multiple conditions.

#!/bin/bash

num=7

if [ $num -eq 10 ]
then
    echo "Number is 10."
elif [ $num -lt 10 ]
then
    echo "Number is less than 10."
else
    echo "Number is greater than 10."
fi

Explanation:

  • -eq: Tests if the numbers are equal.
  • -lt: Tests if the number is less than the specified value.
  • The script will print “Number is less than 10.” because num is 7.

Important Notes:

  • When checking numbers in bash, you should use -eq for equality, -gt for greater than, -lt for less than, etc.
  • When working with strings, use == or != for equality and inequality, respectively.
  • Use "$variable" (quotes around variables) to handle cases where variables may contain spaces or special characters.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x