Brief on Conditional Structure if | then | elif | else | fi | Linux in Pakistan
Tutorials

Brief on Conditional Structure if | then | elif | else | fi

Sometimes you need to determine different courses of action to be taken in a shell script, depending on the success or failure of a command. The if the construction allows such conditions, thus creating a bypass flow through conditional evaluation.

If the structure:
if … then … elif … else … fi

Syntax:
if [TEST]; Then
test commands …
elif [SENAO-TEST]; Then
Command-else test …
else
command-else …
fi

The list TEST is executed, and if its return status is zero, the line commands-test is performed, but the list SENAO-TEST is executed, and if its return status is zero, the line -else-test commands it is performed, otherwise the line Sino-command is executed. The return status is the exit status of the last command running, or zero if no condition tested is true. The TEST most often involves numerical comparison tests or chain, but can also be any command that returns a zero status with can and some other state if he were to fail.

Expressions used with if

The table below contains the so-called primary expressions that make up the command TEST or a list of commands. These expressions are enclosed in brackets ‘[]’. If the expression is omitted the condition evaluates to false, otherwise as true.

[-a FILE]
True if FILE exists.
[FILE b]
True if FILE exists and is a block special file.
[FILE -c]
True if FILE exists and is a character special file.
[-d FILE]
True if FILE exists and is a directory.
[FILE -e]
True if FILE exists.
[-f FILE]
True if FILE exists and is a regular file.
[FILE g]
True if FILE exists and its SGID bit is set.
[FILE -h]
True if FILE exists and is a symbolic link.
[-k FILE]
True if FILE exists and its sticky bit is set.
[-p FILE]
True if FILE exists and is a named pipe (FIFO).
[-r FILE]
True if FILE exists and is readable.
[-s FILE]
True if FILE exists and has a size greater than zero.
[-t FD]
True if file descriptor FD is open and refers to a terminal.
[-u FILE]
True if FILE exists and its SUID (set user ID) bit is set.
[-w FILE]
True if FILE exists and is writable.
[-x FILE]
True if FILE exists and is executable.
[-the file]
True if FILE exists and is owned by the effective user id.
[-G FILE]
True if FILE exists and is owned by the effective group ID.
[-L FILE]
True if FILE exists and is a symbolic link.
[-N FILE]
True if FILE exists and has been modified since the last reading.
[-S FILE]
True if FILE exists and is a socket.
[Nt FILE2 FILE1]
True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.
[FILE1 FILE2 -ot]
True if FILE1 is older than FILE2, or is FILE2 exists and FILE1 does not.
[FILE1 -ef FILE2]
True if FILE1 and FILE2 refer to the same device and inode numbers.
[-o OptionName]
True if the shell option “OptionName” is enabled.
[TEXT z]
True length is “TEXT” is zero.
[-n STRING] or [TEXT]
True, if the length of “TEXT” is different from zero.
[Text1 = STRING2]
True if the texts are equal. “=” Can be used instead of “==” for strict compliance with POSIX.
[String1! = STRING2]
True if the text is not the same.
[Text1 <STRING2]
True if “string1” type before “string2” lexicographically in the current location.
[Text1> STRING2]
True if “string1” types after “string2” lexicographically in the current location.

Arithmetic operators
Arithmetic operators are used to perform many of the familiar arithmetic operations involving the calculation of numerical values represented by literals, variables, other expressions and constants. Also classified with arithmetic operators are binary operators that act at the level of individual bits of the operands and shift their bit patterns to the left or right.

[Eq EXP1 EXP2]
True if EXP 1 equals EXP2.
[EXP1 EXP2 -ne]
True if EXP 1 is not equal to EXP2.
[-lt EXP1 EXP2]
True if EXP 1 is less than EXP2.
[EXP1 EXP2 -l]
True if EXP 1 is less than or equal to EXP2.
[-gt EXP1 EXP2]
True if EXP 1 is greater than EXP2.
[EXP1 EXP2 -g]
True if EXP 1 is greater than or equal to EXP2.

Logical Operators

Logical operators evaluate multiple bloc conditional as if fo s are part of a single expression conditional one or more elements pr is -defini of.
[EXP 1 – the EXP2]
True if EXP 1 or EXP 2 is true.
[EXP 1 – the EXP2]
True if EXP 1 and EXP2 are Green adeiros.
[[EXP1 || EXP2]]
True if EXP 1 or EXP2 is true. (Only expansion )
[[EXP1 && EXP2]]
True if EXP 1 and EXP2 are true. (Only expansion)
[! EXP ]
True if EXP is false. ! Not logical (NOT)

The use of double brackets ‘[[exp]]’ determines whether the condition is evaluated an expansion. Expressions are composed of the name of primary and expansion are not performed on the words between the ‘[[exp]]’; Expansion tilde ‘~’, growth parameters and variables, arithmetic expansion, command substitution, replacement and removal processes are carried quotes. Conditional operators such as -f must be unquoted to be recognized as primary.

When operators as ‘==’ and ‘! =’ Are used, the chain of direct operator is considered a pattern. The return value is ‘0’ if the string matches or does not match the pattern, otherwise 1. Any part of the pattern may be quoted to force it to be matched as a string.

The list command – test that follows the statement Then can be any valid command , executable program, executable shell script or shell statement , with ex  if the closure. The Then and fi are considered separate statements in the shell. Therefore, when issued on line command , These are separated by a point.

If the application 1. Operators Conditional 1.1 Checking if a file exists.

# Check that the file / etc / group ‘exists.
if  [ -e / etc / group ] ; Then
echo ‘File exists’ else echo “File does not exist’ fi

# Output
file exists

The conditional operator ‘ -e ‘ checks whether the specified file exists by running the first block of statement if the condition is true , otherwise execute the instructions else .

——————————————————————————————————————————–

1.2 Check if the user has write permissions on a particular file.
# Tests whether the user has write access to the file.
if  [ ! -w / etc / shadow ] ; Then
echo ‘You do not have permission to write this file.’ exit 1   # Terminate fi

# Output
You do not have permission to write this file.

The condition checks if the current user has write permissions on the file / etc / shadow and use the logical operator ! (No), reverses the condition. If it is true it becomes false and vice versa . In this case it was treated only the false condition, ie, the statements are executed only if the user does not have write permissions. 1.3 Testing if an option is on the shell.

——————————————————————————————————————————–

# Check that the ‘noclobber’ option is enabled.
if  [ -o noclobber ] ; Then
# Print message
echo  ‘Your files are protected’
fi

# Output
Your files are protected

Checks if the option noclobber is active. When activated the system does not allow write data to a file using the redirectors ‘>>’ or ‘>’. These options are set using the set command + | – option.

——————————————————————————————————————————–

2 . The peradores arithmetic .

A conditional test applied and m a list in érica must use the arithmetic operators .

2 .1 Tests if the value of the variable var is greater than 9 .
# Assigns value
var = 17

# Check that the value stored in ‘var’ is greater than 9
if  [  $ var -gt 9 ] ; Then
echo ‘Greater than 9’ else echo “Less than or equal to 9 ‘ fi

# Output
Greater than 9

The conditional expression is executed; If the value of var is greater than 9 , the first block of statements is executed, otherwise the block else runs.

——————————————————————————————————————————–

2 . 2 Check ing the value of var equals 12 .
# Assigns value
var = 10

# Check that value stored in ‘var’ is equal to 12
if  [  $ var -eq 12 ] ; Then
echo ‘Same as 12’ else echo “Unlike 12 ‘ fi

# Output
Unlike 12

The expression is tested; As the value stored in the variable is different from 12 and there is no more conditional tests, the block else runs.

——————————————————————————————————————————–

2 .3 Running multiple conditional testing.
# Assigns value
a = 3

# Testing the value of a.
if  [  $ in eq 2 ] ; Then
echo ‘equals 2’ elif [ $ in eq 3 ] ; Then echo ‘Equal to 3’ else echo ‘Unlike 2:03’ fi

# Output
Equal to 3

The first conditional test runs, then the expression is marked as false because the value of a is other than 2 ; Then the second conditional test is run and the expression is evaluated as verdadeir to as the value a is equal to 2 . The block else does not run.

——————————————————————————————————————————–

3 . Logical Operators 3 .1 Checking whether a number is within a range.

# Variable
a = 14

Operator # l ógico
# Check if ‘a’ is greater than or equal to 10; Or if ‘a’ is less than or equal to 20.
if  [  $ a -g 10 -o $ a -lt 20 ] ; Then
echo “The number is greater than 10 and less than 20 ‘ else # Otherwise echo ‘ Out of Range ‘ fi

# Output
The number is greater than 10 and less than 20

The expression containing the logical operator ‘ -o ‘ returns true if any of the conditions evaluates to true . That is, if a is greater than or equal to 10 or if a is less than or equal to 20 ; Otherwise the instruction else is performed.

——————————————————————————————————————————–

3.2 Checking if both conditions are true.
Variables #
num1 = 5
num2 = 10

Conditional Operator #
# Check if “num1 is equal to 5 and” num2 is equal to 10
if  [  $ num1 eq 5 -a $ num2 eq 10 ] ; Then
echo ‘is num1 and num2 equal to 5 equals 10’ fi

# Output
is num1 and num2 equal to 5 is equal to 10

The logical expression with the operator ‘ -a ‘ only returns true if both conditions are true .

The logical operators ‘ -a ‘ and ‘ -o ‘ can not be used in expansive if’s. That is, when we use double brackets ‘ [[…]] ‘. In such cases the operators is used || (OR) and && (E).

——————————————————————————————————————————–

4. Comparing strings

4.1 Checking whether the strings are equal.
# Variable
string = ‘Shell’

# Compare the value stored in ‘string’ with ‘shell’
if  [  “$ string”  =  ‘Shell’  ] ; Then
echo ‘Equal’ else # Otherwise echo ‘Different’ fi

# Output
Equals

The value string is compared to the expression S hell , if the condition is true , executes the instructions of the first block if condition executed the instructions else. The method is compared bit by bit, where differences between uppercase and lowercase characters are consider.

——————————————————————————————————————————–

4.2 Testing difference between strings.
# Variable
string = ‘Shell 2 ‘

# Compare the value stored in ‘string’ with ‘shell’
if  [  “$ string”  =!  ‘Shell’  ] ; Then
echo ‘ Different s ‘ else # Otherwise echo ‘ Equal ‘ fi

# Output
Many different

——————————————————————————————————————————–

4.3 Checking if the variable is empty.
# Test if the environment variable ‘PATH’ is empty.
if  [ -z “$ PATH”  ] ; Then
echo ‘Empty’ else # Otherwise # Prints the variable content. echo $ PATH fi

# S around the
/ Usr / local / sbin: / usr / local / bin: / usr / sbin: / usr / bin: / sbin: / bin: / usr / games / usr / local / games: / snap / bin

We may also use a negated condition to replace the ‘z’ operator in the conditional expression. Example. Replace [-z “$ PATH”] by [! “$ PATH”] ; Would obtain the same result.

——————————————————————————————————————————–

5. Compound Expressions

To treat compound expressions use double brackets is required in the declaration of if. Example. ‘ If [[expression]]; then … ‘. At first a good portion of users are starting to program in shell, do not have the good practice of placing the variables between the quotes “$ var.” Omit the quotes causes the contents of the variable is interpreted as different elements, if there is a composite stored expression.

Example:
# Simple expression
name = ‘Fernanda’

# Using the variable without quotes
if  [  $ name  =  ‘Fernanda’  ] ; Then
echo ‘Like’ else echo ‘Different’ fi

# Output
Equal

Although not declare the variable in double quotes, no error occurred; Because the expression stored in the variable was simply consisting of a single element

——————————————————————————————————————————–

using the same example, but storing a compound name.
# Expression composite
name = ‘Fernanda Souza’

# Using the variable without quotes
if  [  $ name  =  ‘Fernanda Souza’  ] ; Then
echo ‘Like’ else echo ‘Different’ fi

# Output
bash: [: too many arguments
Different

It returned an error message informing the excessive use of arguments. The if statement is the return code executing instructions in else . (Setting the condition as false-generated error)

——————————————————————————————————————————–

with double brackets.
# Compound Expression
name = ‘Fernanda Souza’

# Using the variable without quotes, but with double brackets.
if  [[  $ name  =  ‘Fernanda Souza’  ]] ; Then
echo ‘Like’ else echo ‘Different’ fi

# Output
Equal

The use of double brackets [[..]] causes the interpreter if the expression only with a string composed protected.

6. Regular expressions. The if used the additional binary operator ‘ = ~ ‘ . The same precedence as ‘==’ and ‘! =’. The string of characters to the right of the operator is considered an extended regular expression and combined with compliance (as in a regular expression). The return value is 0 if the string matches the pattern, otherwise 1. If the regular expression is syntactically incorrect, the return value of the conditional expression is 2. If the option no case match shell is habitability to, the expression is evaluated without It has character s alpha. Any part of the pattern may be quoted to stress will it to correspond with a string . Sub strings matched with sub entity expressions parent ESEs within the regular expression are saved in the array BASH_REMATCH . The element BASH_REMATCH with index 0 is the portion of chain combined in the regular expression. The element index ‘ N ‘ is the part of the chain corresponding to the n th of the expression between brackets. The expressions can m be combined using the following operators, listed in descending order of precedence: (Expression) Returns the value of the expression. This can be used to substitute for the normal precedence of operators. 6.1 Check if number is even.

Value #
a = 3212

# Regular expression that evaluates if the value stored in ‘a’ is even
if  [[  $ a  = ~ ^ [ 0-9 ] * [ 02468 ] $ ]] ; Then
echo “The number is even” else # Otherwise. echo “The number is odd ‘ fi

# Output
The number is even

The regular expression within a conditional expression must be declared without the use of single quotes ( ‘) or double ( “), because these characters are interpreted in a literal way. 6.2 Checking if the value stored in the variable is of type number.

——————————————————————————————————————————–

# Value
a = 12

# Check that the value is a negative or positive integer.
if  [[  $ a  = ? ( + | – ) + ([ 0-9 ])  ]] ; Then
echo ‘Number’ else echo ‘String’ fi

# Output
Number

——————————————————————————————————————————–

6.3 Validating part of the expression.
# Variable
name = ‘Julian’

# Casa any name that starts with ‘July’.
if  [[  $ name  = July * ]] ; Then
echo ‘true name’ else echo ‘Invalid’ fi

# Output
valid name

Every expression that start with ‘July’ is validated. Example: Julian, Julia, July, pollack, July, etc.

——————————————————————————————————————————–

7. Testing return code The return code of the last executed command is stored in the variable $? . Indicating whether the command was executed correctly (Returns: 0) or there is a fault (Unlike: 0). Read: Functions . 7.1 Checking if a file exists.

# Accesses the file if it exi stir , redirecting standard output to the black hole.
ls file &> / dev / null

# Checking the return code
if  [  $? eq 0 ] ; Then
echo ‘File exists.’ else echo ‘File not found. ” fi

# Output
File not found.

The command ls tries to access the file. The reason to redirect the command output to / dev / null , it is because only the return code that matters. The tests if the value is $? is equal to 0 (zero) indicates that the file exists, otherwise it does not exist. Attention when evaluating the variable $? Make sure that if the subsequent command structure is to be tested. Using the example above, just by entering the command echo ‘from the command to be tested and the conditional test.

——————————————————————————————————————————–

# Accesses the file if it exi stir , redirecting standard output to the black hole.
ls file &> / dev / null

# WRONG
echo

# Check the return code from the command ‘echo’
if  [  $? eq 0 ] ; Then
echo ‘File exists.’ else echo ‘File not found. ” fi

# Output

file exists.

Note that even the file does not exist, the conditional test was evaluated as true , because the return code stored in $? It is the command echo (last executed command).

We can evaluate the return of the command directly, declaring it the structure command-test of the if, omitting the brackets ‘[…]’.

——————————————————————————————————————————–

Example: If command …; then … fi

7.2 Verifying an existing file.
# Execute the command and tests the return code.
if ls / etc / group &> / dev / null; Then
echo ‘File exists.’ else # Otherwise echo ‘File not found. ” fi

# Output
file exists.

——————————————————————————————————————————–

7.3 Checking whether a string is present in an expression.
# Expression
QUOTE = ‘I am studying and learning a lot about Linux. Only freedom. ‘

# Search the word ‘Linux’ in the expression stored in ‘SENTENCE’
# grep running in silent mode.
if echo  $ SENTENCE | grep -iwq ‘Linux’ ; Then
echo ‘You are talking about Linux.’ fi

# Output
You’re talking about Linux.

The echo prints the contents of the variable, redirecting to grep to search the standard ‘ Linux ‘ in silent mode (q). Returns 0 (zero) if the default fo r found, otherwise returns 1.