If-else, elif Conditional Execution in Shell Script

Conditional Execution


If else


It tests the result of a condition and if the condition is true then executes statement1, otherwise if else part is there then it executes the statement2.

if condition
then
statement1
else
statement2
fi



if else condition
if else condition

Nested if - then - if statements

if condition
then
if condition
statement1
       fi
fi



Nested if else statements


For checking multiple conditions, the program can be written as

if condition
then
statement1
      else if condition
      statement2
      fi
else
statement 3
fi

Here else if can be replaced as elif also.


Example


#!/bin/sh
if [ -f info ]
then
echo “info is a file”
    elif [ -d info ]
    then
    echo “info is a directory”
else
echo “info is neither file nor directory”
fi



this programs the file info either it is regular file or directory or other.



No comments: