Bash scripts are computer programs consisting of a series of commands that may be used in the command-line environment. They are commonly used for automating repetitive tasks in Linux systems.
Variable Assignment
- The syntax below is used when assigning values to variables in Bash.
variable=value
echo $variable
- The variable can be accessed in the code by prefixing the variable name with a '$' e.g. $variable as illustrated above.
Types of Variables
- There are two types of variables in Bash.
- Global variables: accessible anywhere in the script, regardless of scope, by default, every variable we create in Bash is global.
- Local variables: confined to the section of code or function in which they are declared, they are created using the local keyword.
Difference between global and local variables.
#!/usr/bin/env bash
GLOBAL_VAR="This is a global variable"
function example {
echo $GLOBAL_VAR
}
test # outputs: This is a global variable
#!usr/bin/env bash
function test {
local LOCAL_VAR="This is a local variable"
echo $LOCAL_VAR
}
test # outputs: This is a local variable
echo $LOCAL_VAR # outputs nothing
Looping in Bash
There are three types of loops used in Bash: for loop, while loop and until loop. These loops have varying syntax but can carry out similar tasks when implemented in a Bash script.
for loop
- Allows for specification of a list of values.
for NAME [in LIST ]; do COMMANDS; done
- NAME represents the variable name; often denoted as ‘i’, LIST can be a list of words, strings, numbers etc, and COMMANDS represent any operating system commands, program or shell statement.
- The loop will terminate once the NAME has taken on every value from LIST and no items are left in LIST.
#!/usr/bin/env bash
for i in {1..5};
do
echo $i
done
while loop
- Allows for repetitive execution of a list of commands, as long as the command controlling the while loop is true.
while CONTROL-COMMAND; do CONSEQUENT-COMMANDS;done
- CONTROL-COMMAND can represent any commands that will exit on success or failure.
- The CONSEQUENT-COMMANDS can be any program or script.
- When the CONTROL-COMMAND fails, i.e., is no longer true the loop exits and the done statement is executed.
#!/usr/bin/env bash
i=1
while [[ $i -le 10 ]];
do
echo "While loop"
(( i += 1))
done
until loop
- Allows for repetitive execution of a list of commands as long as the TEST-COMMAND is false, once it succeeds, the loop terminates.
until TEST-COMMAND; do CONSEQUENT-COMMANDS; done
- TEST-COMMAND can be any command that can exit on success or failure, CONSEQUENT-COMMANDS can represent any script or Linux command.
#!/usr/bin/env bash
i=0
until [ $i -eq 10 ];
do
echo "Bash Scripting"
(( i += 1))
done
References
https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_01.html
Top comments (0)