Control structures in shell scripting
If | Case | For | While | Until
Versión en español: Estructuras de control en shell scripting
Shell scripts execute commands in a sequence similar to other programming languages and control structures can change the order in which these commands are executed.
Conditionals
Conditional structures are those that allow you to execute an action if a certain condition is met. The most common control structure in shell scripting is the if
command. This command allows you to evaluate an expression and, if the condition is met, execute a block of commands.
if
The following is an example of if
:
#!/bin/bash
if [ condition ]; then
Do something
elif [ condition 2 ]; then
Do something
else
Do something
fi
The spaces between the condition and the square brackets are required (in bash).
An alternative way to construct the conditions is [[ condition ]].
The end of the structure is closed with the word fi (if backward).
Multiple operators can be used in conditions such as:
Strings:
[ "abc" \= "abc" ] => If string 1 is exactly equal to string 2 (true).
[ "abc" != "abc" ] => If string 1 is not equal to string 2 (false).
[[ "abcd" = bc ]] => If string 1 contains string 2 (true).
[[ "abe" = "ab**[cd]**" ]] => If the third character of string 1 is c or d (false).
[ -z $var ] => If the variable is empty or null.
[ -n $var ] => If the string length is not 0.
Numbers:
[ 5 -eq 5 ] => If number 1 is equal to number 2 (true).
[ 5 -ne 5 ] => If number 1 is not equal to number 2 (false).
[ 5 -gt 5 ] => If number 1 is greater than number 2 (false).
[ 5 -ge 5 ] => If number 1 is greater than or equal to number 2 (true).
[ 5 -lt 5 ] => If number 1 is less than number 2 (false).
[ 5 -le 5 ] => If number 1 is less than or equal to number 2 (true).
Files:
[ -e file ] => If the file exists.
[ -f file ] => If it is a regular file.
[ -d /dir ] => If the parameter is a directory.
[ -s file ] => If the file size is different from 0.
[ -r file ] => If the file has read permissions.
[ -w file ] => If the file has to write permissions.
[ -x file ] => If the file has to execute permissions.
Logical:
[ ! -e file ] => Denies the result.
[ condition ] && [ condition ] => Both conditions must be true for the result to be true.
[ condition ] || [ condition ] => One of the conditions must be true for the result to be true.
case
The following is an example of case
:
#!/bin/bash
case $choice in
1)
Do something
;;
2)
Do something
;;
*)
Do something
;;
esac
The space (or line break) between the parenthesis and the command is required.
Each block within the case must be closed with ;; .
The closing ;; can be placed at the end of the last command, but as a good practice, it is placed on a new line to aid readability.
Loops
Loop structures allow a block of commands to be executed repeatedly until a condition is met. In shell scripting, there are two types of loop structures: for
and while
.
for
The following is an example of for
:
#!/bin/bash
for variable in lista; do
Do something
done
- The words do and done indicate the start and end of the instruction block.
There are multiple ways to define the list of elements such as:
Numbers:
#!/bin/bash
for number in 1 2 3 4; do
echo $number
done
- It is also possible to use {0..4} to represent the above list.
Files in a directory:
#!/bin/bash
for file in *; do
echo $file
done
- The asterisk (*) is a wildcard signifying all files in the current directory.
Strings of characters:
#!/bin/bash
for string in "Hello" "World"; do
echo $string
done
Command output:
#!/bin/bash
for directory in $(ls); do
echo $directory
done
It is also possible to write the for
loop as follows (similar to other programming languages):
#!/bin/bash
for (( number = 0 ; number <= 4; number++ )); do
echo $directory
done
while
The following is an example of while
:
#!/bin/bash
while [ condition ]; do
Do something
done
Since the condition is evaluated at each iteration of the loop, if it never becomes false, it will be an infinite loop, to avoid this it is important to make sure that the condition eventually becomes false or use a break
statement as seen below:
#!/bin/bash
counter=1
while true; do
echo $counter
if [ $counter -eq 10 ]
then
break
fi
counter=$((counter + 1))
done
In this example, the "while" loop runs indefinitely with the condition true
. At each iteration, the value of counter
is printed and then incremented by 1. If the value of counter
equals 10, the break
statement is executed, which stops the loop.
The break
statement is useful in loops to stop loops at a specific time if a certain condition is met. This helps to avoid infinite loops and to improve the efficiency and control of the code.
until
The following is an example of until
:
#!/bin/bash
until [ condition ]; do
Do something
done
There may be situations where it is necessary to skip a specific iteration and continue with the next one, this is possible by using the continue
statement as shown below:
#!/bin/bash
counter=0
until [ $counter -eq 10 ]
do
counter=$((counter + 1))
if [ $((counter % 2)) -eq 0 ]
then
continue
fi
echo $counter
done
In this example, we define a counter
variable counter initialized to 0. The "until" loop will continue until the value of counter
equals 10. At each iteration, the value of counter
is increased by 1. Then, it is evaluated whether the remainder of the division of counter
by 2 equals 0. If this condition is met, the continue instruction is executed, which skips the current iteration and continues with the next one. If the condition is not met, the value of counter
is printed.
As a result, this code will print the odd numbers 1 through 9.
The continue
statement is useful in loops to skip a specific iteration if a certain condition is met, without having to exit the loop completely. This helps improve code efficiency and control, and is a good coding practice for writing readable and maintainable code.
If you found it helpul, like/share this article so it reaches others and if you're new in the blog, we'd appreciate it if you follow us! We try to write articles to keep track of everything we've learned or personally want to read, what we love to know and how we did it or get ideas from readers.
See you back soon!