Bash Scripting Tutorial
Bash Scripting Tutorial
Emre Koşar
BASH SCRIPTING
Table of Contents
What is Bash?............................................................................................................................................................................................................ 2
Why Should We Use Bash Scripting?.................................................................................................................................................................. 2
Introduction to Bash Scripting ................................................................................................................................................................................... 3
Switching to Bash................................................................................................................................................................................................ 3
Creating Our First Bash File ................................................................................................................................................................................ 3
Properly Writing Bash Script ............................................................................................................................................................................... 5
Variables in Bash Scripting ....................................................................................................................................................................................... 6
Using Variables in Bash Script Files .................................................................................................................................................................... 6
Examples ............................................................................................................................................................................................................. 7
Mathematical Operations in Bash Scripting .............................................................................................................................................................. 8
Using Variables in Mathematical Operations ....................................................................................................................................................... 9
If Statement in Bash Scripting ................................................................................................................................................................................... 9
Creating If-Else Conditional Blocks in Bash Scripting ........................................................................................................................................ 9
Checking for Existence of a File ....................................................................................................................................................................... 10
Checking for Existence of a Directory............................................................................................................................................................... 10
Creating a Bash Script File to Install Package ................................................................................................................................................... 11
Exit Codes in Bash Scripting ................................................................................................................................................................................... 11
Examples ........................................................................................................................................................................................................... 13
While Loop in Bash Scripting ................................................................................................................................................................................. 14
Until Loop in Bash Scripting ................................................................................................................................................................................... 15
For Loop in Bash Scripting ..................................................................................................................................................................................... 16
Data Streams ........................................................................................................................................................................................................... 17
Functions in Bash Scripting..................................................................................................................................................................................... 19
Passing Arguments to Function ......................................................................................................................................................................... 19
Return Values .................................................................................................................................................................................................... 20
Variable Scopes ................................................................................................................................................................................................. 20
Overriding Commands ...................................................................................................................................................................................... 21
Case Statements in Bash Scripting .......................................................................................................................................................................... 22
Arrays in Bash Scripting ......................................................................................................................................................................................... 23
Creating and Printing Array ............................................................................................................................................................................... 23
Iterating Elements Over Array ........................................................................................................................................................................... 24
Printing Array Indices ....................................................................................................................................................................................... 24
Things to Pay Attention in Bash Scripting ............................................................................................................................................................... 25
Sources .................................................................................................................................................................................................................... 26
1
BASH SCRIPTING
What is Bash?
Bash stands for Bourne-Again Shell. It is a command line interpreter and widely used in
GNU/Linux OS. Bash is one of the most popular shell environment. Shell refers to a program
that provides a command-line interface for interacting with an OS. Shell allows us to enter
commands and then it returns us with the appropriate results of provided commands as output.
As we can see on the picture above, a command (ls) has been entered and as result of this
process, we are able to see the output of that command. In case of entering an incorrect
command, we’d get an error as command not found. That’s because Shell won’t be recognizing
the random commands.
Automation: Shell scripts allow us to automate repetitive tasks and processes, saving time and
reducing the risk of errors that can occur with manual execution.
Portability: Shell scripts can be run on various platforms and operating systems, including
Unix/Linux/macOS and even Windows.
Debugging: Shell scripts are easy to debug, and most shells have built-in-debugging and error
reporting tools that can help identify and fix issues quickly.
Integration: Shell scripts can be integrated with other tools and applications such as databases,
web servers, cloud services etc. Shell scripts allow for more complex automation and system
management tasks.
2
BASH SCRIPTING
As you can see, I’m running ‘Z shell’ which is one another Shell
environment. Let’s switch to the Bash.
3
BASH SCRIPTING
• Press CTRL+O,
• Press ENTER,
• Press CTRL+X.
The file has been saved. To execute the Bash File, we need to give executable permission to it.
If you come so far, you can run the file you’ve created.
We can add many more commands into Bash file we desire. For instance:
4
BASH SCRIPTING
The two commands in the Bash file don’t represent the actual structure of Bash script. These
were meant to be understand the logic. In addition, Bash files can have if statements, loops and
things like that. I’ll be demonstrating how to control our Bash file according to our points.
Let’s add one more thing. I will be adding something to show how to combine echo (print) and
another shell command.
As you can tell from the output, each line of scripts printed on
different lines.
5
BASH SCRIPTING
• Whenever we reference a variable in Bash, we have to put a Dollar sign in front of the
name of the variable. Otherwise, it’s not going to work exactly as we might expect.
• Let’s say a previously undeclared variable name has taken part on the ‘echo’ line. Bash
will return empty (null) result.
• Also keep in mind that if you declared variables in terminal and once you exit the
terminal and reopened it you can’t ‘echo’ them because they are all gone since the session
has closed.
6
BASH SCRIPTING
• One more thing to pay attention is that we need to place variables in between double
quotes. Instead, if we placed in between single quotes, Bash would ignore the value
corresponding the variable, it’d print the variable name itself.
Examples
In this example, a variable called ‘my_word’ has
assigned to ‘great’ value. The purpose is to not
write ‘great’ in each line recursively. This type of
usage also gives the opportunity to change the
word in one shot.
7
BASH SCRIPTING
• The $SHELL variable is one of the default variables in our Shell environment. There are
many more default variables such as $USER , $OSTYPE etc. These kinds of variables
are always declared. Please make sure that the variables you declare do not have the same
name as these default variables.
HINT: If you want to see default variables in your Shell environment, you can run the ‘env’
command on your terminal.
8
BASH SCRIPTING
Firstly, the variable has been defined and then simply placed its
name after Dollar sign.
HINT: If you’re coding on terminal (not on IDE) and have to indent a Tab, don’t press Tab
button directly. Instead, press the Space button 4 times.
9
BASH SCRIPTING
10
BASH SCRIPTING
In case of running an invalid command or looking for non-existing file/directory, obviously we’ll
get error. So, the exit status code won’t be zero. Here is how it looks for particular case:
11
BASH SCRIPTING
12
BASH SCRIPTING
Based on the recent script, let’s get closer to real-life script by modifying it.
Examples
The purpose of this script is to see if the provided
directory exists or not. To do that if-else statement is
used. By the way, the directory specified in this example
exists the system.
13
BASH SCRIPTING
Reason why we got exit code of zero is because as you can remember, ‘$?’ gives the most recent
command’s status. Since the most recent command executed on the system is ‘echo’ under if-else
statement, exit status code will be zero.
As expected, the script counted all the way up to 10. When it hits 10,
the script terminates itself.
Let’s do one more example. In the subsequent example, there will be fresh commands and
methods.
Let’s try to understand the script line by line.
First, to prevent infinite loop, we used ‘num’
variable inside the while loop as it’s defined
as 1. Instead of giving the directory inside
the script, we would go with getting it from
user. In order to do that, we used ‘read’
command which is used for getting input. On
top of that, ‘-p’ parameter is used for printing
the provided message and after the message ‘dir’ is input variable. If we are looking to while
loop, there are two conditions provided. What they are responsible for is to check if the directory
exists or not and in order to prevent infinite loop, to check ‘num’ variable to see if it’s less or
equal to 1. The purpose of ‘if’ statement is to inform that directory does not exist on the system.
It only works when the user gives an invalid directory.
14
BASH SCRIPTING
15
BASH SCRIPTING
16
BASH SCRIPTING
Data Streams
In general, the definition of Data streaming is the continuous transfer of data at a high rate of
speed. Data streams are collecting data from various data sources. There are three types of Data
Streams in computer programming. In previous sections, there is one type of data stream that is
highly used, which is ‘STDOUT’ (Standard Output). For instance, ‘pwd’ or any other commands
that print something on the screen are example of Standard Output. Let’s talk about the other
type of data stream. For instance, let’s assume that you wanted to list a non-existed directory and
you typically get error. That’s called ‘STDERR’ (Standard Output). The last type of data stream
is called ‘STDIN’ (Standard Input). It’s used when the program reads its input data.
Let’s clarify the standard error and standard output by using the ‘find’ command.
The command is ‘find /etc -type f’ which means find any files
under ‘/etc’ directory. The point to keep in mind is that the
command will print both STDOUT and STDERR. In this case,
standard errors would be ‘Permission Denied’ alert since the
command executed as user and user can’t see what’s inside of
some files. So, if the command was executing as root, there would
be no error for this case.
If we don’t want to see any errors, we can distinguish standard error and standard output. Also
keep in mind that this could be useful while writing a Bash Script automation or something like
that.
17
BASH SCRIPTING
What if we want to redirect both standard output and standard errors into a particular place? Let’s
find out.
18
BASH SCRIPTING
19
BASH SCRIPTING
Return Values
A return value is produced and returned to the calling method by a function after it completes its
execution. In computer programming, the concept of return value for functions is used to send
data back to the original calling location. However, Bash doesn’t allow us to do this. It allows us
to set a return status code. In Bash scripting, the return value is assigned to ‘$?’ variable. Let’s
see it in example.
Variable Scopes
A variable is ‘global’ by default. Global variable allows us to use the variable wherever we’d like
inside the script file. When we create a variable inside of a function, it’s a ‘local’ variable, which
can only be used inside of that function. To create a local variable, we have to use ‘local’
keyword in front of the variable name itself. Let’s see it in the example.
20
BASH SCRIPTING
Overriding Commands
In Bash scripting, it is possible to name a function as the same name as a Bash command. In case
of naming the function with a Bash command, that particular command will execute the orders
inside the defined function, not the default orders. Let’s say we want to run ‘ls -la’ but we forget
the parameters every time. If we could just create a function name ‘ls’ inside of a Bash file and
let it execute ‘ls -la’ every time the function called, we would have achieved this. Let’s check
how it works.
Inside of the function, there is a keyword called
‘command’. When we have a function with the
same name as a command, we have to put the
‘command’ keyword in front of the command
itself. Otherwise, it won’t work.
21
BASH SCRIPTING
22
BASH SCRIPTING
Let’s talk about how to print the arrays. As you remember, when printing the variables, we have
used ‘$’ before the name of the variable. For arrays, ‘$’ will be used as well, but inside of
quotation marks and curly braces. The first element counts as zero. So if you want to print the
first element of the array, you will be using ‘[0]’. If you looked at the example carefully, you
would see there are ‘[*]’ and ‘[@]’. They both mean to print all of the elements inside the array.
Let’s take a look at the output of the script above.
23
BASH SCRIPTING
As you can see, the ‘for’ loop printed all of the elements of
‘my_array’.
24
BASH SCRIPTING
25
BASH SCRIPTING
Sources
[Link]
zCqSaN2mD4w&pp=iAQB
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
script/
[Link]
[Link]/scripting/newbie_traps
26