introduction to linux linux installation linux filesystem structure user and group management file permission command line interface package manager bash scripting conclusion
list



bash scripting

“the only way to really learn scripting is to write scripts”

Bash scripting is the process of creating bash scripts which are normal text files executed by bash, these files contain bash commands.

Bash scripting is a fast and easy way to automate tasks, which saves time and effort.

Although bash scripting is considered a programming language, this chapter does not encompass every aspect of it. However, it does focus on the fundamental elements necessary for constructing effective scripts.

To create a bash script, you only need to create a file and open it with a text editor then writing bash commands there which will be executed one by one. For example, I will create a file called “script.sh”, a bash script file usually has the extension “.sh” but you can ignore it or use another one.

  1. To create an empty file, open a terminal and run:

touch script.sh

  1. Then open it with a text editor like nano or mousepad (prefer mousepad since it has gui):

mousepad script.sh

a window like this will open:

  1. now write some bash commands separated by a line or a semicolon “;”, for example

    this script will run the commands: echo "linux" and ls
  2. To run the script use the command bash like this:

bash script.



The command echo "linux" print linux and the command ls -a list all files which are the script file and the “.” directory which is the current directory and the “..” directory which is the mother directory of the current directory.

Functions

A function is a block of code (one or more lines of code) that can be used multiple times by only calling the function by its name, this makes the code shorter and easier to understand.

Here is an example of a function in bash

#creating a function named greet
greet() {
           
echo hello
}    
#calling the function
greet

In bash, you can write a comment by using the # sign before the comment. A comment is text created by the programmer to explain something for those who read the code, and it’s not readed by the programming language like bash.

In the previous code we have created a function named “greet” by using the syntax greet() the brackets “{“ and “}” determine the code block of the function, in this case it’s one command “echo hello”.

To execute the code block of a function we call the function by only typing its name like in the previous code greet

Variables and constant 

Imagine variables as boxes, each box has something inside which is called variable value, and each box has a name which is called variable name. Variables are like containers used to store multiple types of data, and to use the data you need to use the variable name.

The difference between variables and constants is that you can change the value of a variable during the script execution but not of a constant.

Let’s get a look on how to use variables:

for example you have this script

var="hi" #creating a variable named 'var' with the value 'hi'
greet() { #creating a function that print the 'var' variable value
echo "$var"
}
greet
#calling the function
var=
"hello" #change the value of the 'var' variable
greet
#calling the function again

In this script we have created a variable named ‘var’ and assigned the value ‘hi’ to it, then we created a function that print the variable value and we call it, so it print ‘hi’, after that, we changed the variable value to ‘hello’ and called the function again and it printed hello.

result:


Sometimes, you need to store the output of a command to a variable, you can do it like this:

variable=$(command)                                   

example :

# Execute a command and store the output in a variable

output=$(ls -a -l)

# Print the stored output

echo -e "The output of the command is:\n $output"

result :

Conditional statements

In Bash, you can use conditional statements to make decisions and execute different blocks of code based on certain conditions. The two main types of conditional statements in Bash are the if-else statement and the case statement.

If-else statement

To create an if-else statement you can use this syntax:

if [ condition1 ]; then
        
#code block to execute if condition1 is true else check condition2
elif [ condition2 ]; then
        
#code block to execute if condition2 is true
        
#you can add more 'elif' if you want or you can use only if or only if and else, that depends on yours needs
else
        
#code block to execute if all conditions is false
fi

example of if-else statement

# Prompt the user to enter a number
echo -n "enter a number: "
read number

# say if the number is positive or negative
if [ $number -gt 0 ]; then
   
echo the number is positive
else
   
echo the number is negative
fi

the condition $number -gt 0 returns true if the variable value of the variable $number is greater than 0 by using the -gt conditional operators. Others conditional operators are:

Operator

Description

-eq

Returns true if two numbers are equivalent

-lt

Returns true if a number is less than another number

-gt

Returns true if a number is greater than another number

==

Returns true if two strings are equivalent

!=

Returns true if two strings are not equivalent

!

Returns true if the expression is false

-d

Check the existence of a directory

-e

Check the existence of a file

-r

Check the existence of a file and read permission

-w

Check the existence of a file and write permission

-x

Check the existence of a file and execute permission

Case statement

Case statements in Bash are used as a form of conditional branching when you have multiple possible conditions to check against a single variable or expression. They provide an alternative to using multiple if statements with multiple conditions.

Here's a simple example to demonstrate the usage of case statements in Bash:

case "$variable" in
        pattern1)
           
# Code to execute if variable matches pattern1
           ;;
        pattern2)
           
# Code to execute if variable matches pattern2
           ;;
        pattern3|pattern4)
           
# Code to execute if variable matches pattern3 or pattern4
           ;;
        *)
           
# Code to execute if variable doesn't match any patterns
           ;;
esac






DMCA.com Protection Status

© 2023 Aimed Guendouz