0% found this document useful (0 votes)
7 views27 pages

Bash Scripting Tutorial

This document is a comprehensive tutorial on Bash scripting, covering topics such as the basics of Bash, creating and executing scripts, using variables, mathematical operations, control structures like if statements and loops, and handling data streams. It emphasizes the advantages of Bash scripting, including automation, portability, and debugging. The tutorial includes practical examples and best practices for writing effective Bash scripts.

Uploaded by

r00tedbe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views27 pages

Bash Scripting Tutorial

This document is a comprehensive tutorial on Bash scripting, covering topics such as the basics of Bash, creating and executing scripts, using variables, mathematical operations, control structures like if statements and loops, and handling data streams. It emphasizes the advantages of Bash scripting, including automation, portability, and debugging. The tutorial includes practical examples and best practices for writing effective Bash scripts.

Uploaded by

r00tedbe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BASH SCRIPTING

Bash Scripting Tutorial with Examples

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.

To give an idea, here is a simple example:

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.

Why Should We Use Bash Scripting?


Bash scripting can lead to some advantages such as automating routine tasks in Unix/Linux
based systems. There are additional advantages of using Bash Scripting. Here are some of them:

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

Introduction to Bash Scripting


Switching to Bash
In order to learn and practice Bash Scripting, you are required to have Linux installed and make
sure that you’re running Bash as Shell. To see which Shell is running our system, we can simply
enter ‘echo $SHELL’ or ‘echo $0’ command.

As you can see, I’m running ‘Z shell’ which is one another Shell
environment. Let’s switch to the Bash.

To switch to Bash from Z Shell, we need to use “chsh” command.


The ‘chsh’ command stands for ‘change shell’. Syntax would be
‘chsh -s <shell path> username’. If you noticed, after applying
the command, Shell environment was still the same. That’s
because reboot is required in order to save the changes.

After rebooting, you can confirm that shell successfully switched


to Bash.

Creating Our First Bash File


When creating a Bash File, we will be following the same path as creating random file. We can
either use ‘touch’ or ‘nano’ commands. The thing to pay attention to here is the file extension.
We need to name our file as format of ‘my_file.sh’.

As you can see, I’ve created a Bash file named


‘first_bash.sh’. Let’s write something simple
inside of that file in order to understand the logic
of Bash files.

3
BASH SCRIPTING

As you can see, the ‘pwd’ (print working


directory) command is written inside of the
Bash file. To save it inside nano text editor,
follow the steps below:

• 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.

As you can see, the file itself doesn’t


have the executable permission. To
give executable permission, simply use ‘chmod +x your_file_name.sh’ command.

After giving executable permission, we


can control if it’s done or not by using ‘ls
-l’ command. If we look at the output of
the second command on the left-hand
side, executable permission is successfully given.

If you come so far, you can run the file you’ve created.

The program returned pwd command’s result.

We can add many more commands into Bash file we desire. For instance:

I’ve added ‘whoami’ command and


that Bash file will return me the results
of both commands.

Since there were two different commands executed on the


script, output of each command would be on different
lines.

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.

Properly Writing Bash Script


First of all, we need to implement a line called Shebang Line. The Shebang is the combination
of the ‘#’ and ‘!’. It is used to specify the interpreter with which the given script will be run by
default. The Shebang Line has an important role in Shell scripting, especially when dealing with
different types of shell.

Here is Shebang Line implemented on our


simple example.

Now, let’s start deep diving with another simple example.

As you can guess, this script will


return ‘Hello world!’

Let’s add one more thing. I will be adding something to show how to combine echo (print) and
another shell command.

Since two different ‘echo’ commands executed,


both sentences are expected to be printed on
different lines. Hence, ‘pwd’ is one another
command itself, it’s also printed on next line.

As you can tell from the output, each line of scripts printed on
different lines.

5
BASH SCRIPTING

Variables in Bash Scripting


Variables are used in programming languages in general. The purpose of using variables is to
hold values or data. These assigned values can change during the execution of a program, hence
the term variable.

In Bash Scripting, declaring a variable is simple. I’ll demonstrate an example.

In the first command, variable has been declared. In the


second command, variables have been printed onto screen.

• 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.

Using Variables in Bash Script Files


I will demonstrate an easy example of using variables in our Bash File.

If you pay attention to the example, there is a Dollar


sign in front of the variable again. So, it doesn’t
matter if we’re on the terminal or not; we have to
use it if variables need to be mentioned.

Values corresponding to variables were printed on the


output where they placed on the script.

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.

‘great’ value has been printed at where its variable


placed on the script.

What if we want to store the output of a shell command inside of a variable?

The corresponding value/method to ‘context’


variable is called subshell. ( $(command) )
Subshell allows us to execute a command in
the background. Speaking of the script, I’ve
declared a variable named ‘context’ and let the ‘ls -l /home/kali/Desktop/bash_scripting’
command to work in the background. After that, I printed the output by using ‘echo’.

In this example, ‘os_name’ variable has


assigned to ‘Linux’ and ‘cwd’ variable has
assigned to output of ‘pwd’ command. On the
last line, as you can see after the Dollar sign,
there is $SHELL variable however we didn’t
declare it. You would think that we might face
an error.

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.

That’s the output of the example. As you can


see, the $SHELL variable returned /bin/bash
value.

HINT: If you want to see default variables in your Shell environment, you can run the ‘env’
command on your terminal.

Mathematical Operations in Bash Scripting


Mathematical operations in Bash Scripting could be useful in some cases. Such as converting
CPU temperature to Fahrenheit. Syntax of mathematical operations in Bash Scripting is a bit
different than other programming languages. In Bash Scripting, there is an evaluate the
expressions command which is ‘expr’.

The ‘expr’ command would run summation,


subtraction and division. But when there is
multiplication, it won’t work. Because asterisk
(*) in Bash is an important thing and it means
everything. Asterisk symbol runs the command
against everything in local directory.

To avoid this type of misuse, use the escape operator. (\)

Thanks to the escape operator, Bash understands


the asterisk symbol as multiplication.

8
BASH SCRIPTING

Using Variables in Mathematical Operations


In this section, we will talk about how to use our pre-defined variables (by us) in Mathematical
Operations. It’s actually simple and similar to what we have covered in previous sections.

Firstly, the variable has been defined and then simply placed its
name after Dollar sign.

If Statement in Bash Scripting


If Statement is one of fundamental construct for decision making structure in programming. In
Bash Scripting, syntax of If Statement is a little bit different. The If Statement must be closed
with ‘fi’ (reversed of if) after the instructions under the statement. In order to give an overview of
the if statements, there is a simple example below.

As how it’s defined above, if statements end with


‘fi’ keyword. The ‘-eq’ represents equal.
Nevertheless, you can free to use equal sign
instead of ‘-eq’ (single equal sign not double). One
more thing is indentations. You have to pay
attention to indentations like I did in the example.
Since the defined number equals 100, hence condition is
provided, we can see the output. If the condition was
false, the program would return empty result.

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.

Creating If-Else Conditional Blocks in Bash Scripting


Now, let’s go further. If ‘else’ statement also used in conditions, the ‘fi’ keyword have to be
placed under else condition. So, there is no need to place ‘fi’ under if condition. As an instance, I
will insert an Else condition to previous script.
As you can see, the ‘fi’ keyword has been moved
from under if block to else block. That’s because the
condition doesn’t end after if block.

9
BASH SCRIPTING

This example returns ‘True statement’ if ‘my_number’ is not equal


to 100. Based on this short explanation, we can simply tell that ‘-ne’
does the same thing as ‘ != ’. By the way, instead of using ‘-eq’ or ‘-
ne’, ‘=’ and ‘!=’ can be used.

Checking for Existence of a File


This topic might be used on real life scenarios. As the topic name suggests, we will learn how to
check if a file exists or not by using ‘if-else’ statement.
The ‘-f’ parameter represents checking for a
file. You can memorize it from ‘file’s initial.
The ‘if’ block checks if there is a file named
‘[Link]’ under /home/kali/Desktop directory.
If it exists, ‘File exists!’ will be printed. If not,
‘File does not exist!’ will be printed.

Checking for Existence of a Directory


Maybe you can guess the parameter used to check for existence of a directory by looking at the
previous section.
The ‘-d’ parameter represents checking for
a directory. You can also memorize it from
‘directory’s initial. The ‘if’ block checks
if there is a directory named ‘emre’.

10
BASH SCRIPTING

Creating a Bash Script File to Install Package


In this section, we’ll write a script which will install the package if it’s not installed on the
system yet. This one might also be useful as automating the process on real life scenarios.

Let’s demonstrate line by line. First, the location


of utility has been declared (to find out you can
run which utility_name). If it’s installed on the
system, only information pops out, nothing will
trigger. However, if it’s not installed, information
pops out and utility (tor) will be installed. Once
the if-else statement is over, command will be triggered.

Exit Codes in Bash Scripting


Each Shell command returns an exit code when it terminates, either successfully or
unsuccessfully. Basically, a certain condition is met, and script should have stopped and
terminated. This is the case exit codes come to play. An exit code of ‘zero’ indicates that the
command completed successfully, and non-zero means that an error was encountered. The
special variable $? returns the exit status of the last executed command.

As you can see, we tried to read an existing file on my


system and didn’t have any error messages. To verify it,
we can print the exit status as in the last command of the
example script by using ‘echo $0’. As mentioned, zero
represents no error.

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

• Why do we need exit status codes?


Assume that you have a task that you are supposed to do tomorrow. But you want it to be
finished by the night, so you have written a script to autonomous the task. The script might fail in
some particular parts. When you wake up, you’ll see where the problem is and take action.

This script is meant to install ‘package’


variable which is ‘torbrowser-launcher’ in this
case.

After executing the script, torbrowser-


launcher was installed on the system, which
means there were no errors. At the bottom of
the output (last line), you can see that the exit
code is zero.

Let’s combine exit status code with if-else statement in a script.

The purpose of this script is if exit


status code equals zero, which means
successful, echo the message above ‘if’
block. If exit status code equals non-
zero, echo the message above ‘else’
block.

As you can see from the bottom


of the output, it was
successfully installed.

12
BASH SCRIPTING

Based on the recent script, let’s get closer to real-life script by modifying it.

The two greater than symbols (>>)


are redirecting the command into
something we obtain. Rather than
printing all of the information on
the screen, what I did by using
‘>>’ was to redirect that output into file.

As of now, output looks clearer. All


of the process is written in the log
file as you can see.

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.

As you can see, we can verify that the


directory exists on the system. So, the exit
status code returned as zero.

What if there was a non-existed directory provided? Let’s find out.

Even though directory doesn’t exist on the system, the


exit status code returned as zero again. Let’s break it
down.

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.

While Loop in Bash Scripting


While Loop is one of the fundamental components of programming. A While Loop is a statement
that iterates over a block of code until the particular condition is met. Syntax of While Loop in
Bash Scripting is not that different than other programming languages. Let’s break it down in an
example.

First things first, a variable called ‘num’ has assigned as 1. In ‘while


loop’, the variable will be printed, and it will increase by 1 until it
reaches 10 (-le parameter means less or equal <=). Inside the loop,
our variable ‘num’ Basically, the script will count to 10 when it’s
executed. Additionally, ‘sleep 0.5’ was added inside the loop for
modern view.

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

This is what the output looks


like when a valid directory is
checked.

This one is what the output


looks like when an invalid
directory is checked.

Until Loop in Bash Scripting


In Bash scripting, there is not just ‘while’ loop. In Bash, there are types of loops that we can use.
They are ‘while’, ‘until’ and ‘for’ loops. As the topic suggests, we will look into the ‘until’ loop.
The syntax of ‘until’ loop is similar to while loop. Let’s break it down in example.
As you can see, the syntax of ‘until’ loop is
similar to ‘while’ loop. This script will return
‘Hello World!’ until the number which is
defined as zero reaches 10 increasing by 1 in
each execution. Once it reaches 10, the script
would stop working immediately. Additionally,
there is a keyword that we didn’t use previously
is used in this script, which is ‘printf’. The
‘printf’ command has almost the same function
as the ‘echo’ command. The difference between
them is the ‘echo’ command sends new line at
the end of the output, unlike ‘printf’ which we have to use ‘\n’ option to create new line after the
message.

On the output, ‘Hello World!’ printed ten times on the


screen. That’s because the loop stopped working after
printed ‘Hello World!’ for tenth times and the number
became greater than ten.

15
BASH SCRIPTING

For Loop in Bash Scripting


For Loop is also one of the core components of programming. By using For Loops in our scripts,
we can perform repetitive tasks and tricky problems in a simple programmatic way. Speaking of
the syntax of For Loops in Bash Scripting, there are two types of usage of For Loops. C-style For
Loop and POSIX-style For Loop. The syntax of POSIX-style similar to Syntax of For Loops in
Python. In general, POSIX-style is preferred for its readability and flexibility, but both of the
styles serve the same purpose. Let’s see it in the examples.

The logic of the script is the same as the first


example of ‘While Loop’ above. Inside of the for
loop, ‘current_number’ variable will equal
whatever the current item iterated in the loop. The
‘{1..10}’ represents 1 to 10 array, so for loop will
print the numbers by order. Additionally, ‘sleep 1’
was added inside the loop for modern view.

The script printed from 1 to 10 and the echo line as it’s


supposed to be.

Let’s write a useful script for the real-life scenarios.

In this script, any files that end with ‘.py’ inside


the specific location will be compressed. After
compressing each one of the files, the operation
will be printed.

As the image proves, all of the files


under the ‘Python_files’ directory had
been compressed.

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.

Adding ‘2>/dev/null’ ignores the standard errors and


prints only the standard output. So, there would be no
single error if ‘2>/dev/null’ parameter is used. What this
‘2>/dev/null’ parameter does is to redirect the standard
errors into /dev/null which is a special place in Linux
file system that wipes out everything in particular place.
However, if you want to see the standard errors, you can
redirect into some another place.

What if we use nothing or 1 instead of 2 while redirecting? Let’s find out.

This command sends standard output to /dev/null. Since


the errors didn’t send anywhere in particular, they will
be printed on the screen as you can see.

17
BASH SCRIPTING

Let’s try ‘1>/dev/null’.

As you can see, this type of redirection returns


standard errors as well. So, number 1 contains the
output of the command which is standard output and
number 2 contains the error messages of executed
command which is standard error. Since these
numbers are redirected into a file, we see the opposite of redirected number as output.

What if we want to redirect both standard output and standard errors into a particular place? Let’s
find out.

To send both standard output and standard errors, the


Ampersand (&) symbol is used. Since both standard
output and standard errors are redirected to a particular
place (in this case it’s /dev/null), there is nothing on the
output.
Enough talking about standard output and standard errors. Let’s have a look at the standard input
(STDIN). As its name suggests, standard input is actually getting information from the user. Let’s
take a look at an example.

As the ‘read’ command and also ‘-p’ parameter


previously used in examples to get user input, it was
representing standard input. As a quick reminder, the
‘read’ command is used for getting input and the ‘-p’
parameter is used for printing a message on the screen
before getting input.

As mentioned above, the message printed before


taking input.

18
BASH SCRIPTING

Functions in Bash Scripting


Functions are one of the key components in computer programming in general. Function allows
us to reuse the set of commands. Think of a function as a small script within a script. It is a small
chunk of code which can be called multiple times when it’s needed.

Let’s take a look at the example.

Let’s break it down line by line. First, user provide


folder and file name separately by order. In this
case, the name of the function is ‘folder_file’.
Inside the function, the folder and the file are being
created on Desktop. After then, if the exit status
code equals to zero, ‘operation successful’ message
will be printed on the screen. At the very bottom of
the page, it can be seen that the function was
called. The important point is ‘dir_name’ and
‘file_name’ variables were added right after the
function name as passing arguments.

After running the script, it first asks for folder


name and then the file name. Since the operation
is successful, in other words, exit status code
equals zero, it printed out the ‘Operation
successful’ message and the information message.

Passing Arguments to Function


In some cases, we might need to pass arguments to the function. What it does is actually sending
data to the function to process when we pass arguments. The arguments are supposed to be
specified right after calling the function. Let’s create a small script in order to fully understand
how it works.

In this script, the point is to pass the numbers as


arguments right after the function and see if it’s
working or not. As a quick reminder, inside of the
function, while defining a multiplication, we have to
use asterisk (*), and it means ‘ALL’ in Bash scripting. So, in order to specify that it’s a
mathematical operation, back slash (\) must be used before asterisk (*).

19
BASH SCRIPTING

As the output proves, the function worked the way we


wanted.

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.

Let’s break the script down. Inside of the function, the


return status was assigned to 15. So, in the output, we
will see the return status value. In addition, the return
status might be variable.

As you can see, the ‘$?’ variable was returned as 15 as


obtained inside the function.

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.

Inside of the function, a few variables were defined.


However, pay attention that two of the variables have
‘local’ keyword before defining them. That particular
keyword makes those variables usable only inside of the
function. So, outside of the function, calling these two
variables would return nothing. But since the
‘my_local_var3’ didn’t define as local variable, it is
callable outside of the function.

20
BASH SCRIPTING

As you can see, in the last line of the output


‘my_local_var’ didn’t return anything since it’s defined as
local variable. But the line which ‘my_local_var3’
variable was called worked correctly even though it’s also
defined inside the function. The reason is ‘local’ keyword.

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.

As you can see, the function lists all files of


/home/kali/Desktop/emre directory.

21
BASH SCRIPTING

Case Statements in Bash Scripting


A case statement in Bash script is used when a decision has to be made against multiple choices.
It’s useful when there are multiple choices needed. Using the case statement instead of nested if
statements would look more readable and reduce the complexity of the script. Additionally, the
case statement has a concept similar to JavaScript or C Switch statement. However, the main
difference between C switch statement and Bash case statement is that Bash Case statement
doesn’t continue to search for a pattern match once it has found one and executed statements
associated with that pattern unlike C Switch statement. Let’s take a look at how the case
statement works.

In this script, the case statement will return a


sentence depending on input from the user. So, the
output sentence will vary based on the input. Let’s
break the case statement down. As variable,
‘car_brand’ variable given for this case which is
the user’s input defined above. The Point of the
case statement is to find out which of the case
matches with the user input. The pipe (|) symbol
separates the two options for a case. The last case
inside of the statement will be executed only if the
user input is different than the other defined cases. To finish the case statement, we must use
‘esac’ which is reversed of case.

In the first execution of the script, I gave


‘mercedes’ as input. So, that triggers the specific
case created for ‘Mercedes’ or ‘mercedes’ input.
In the second execution of the script, I gave a
brand which is not declared under the case
statement. That one triggers the case created for
all of the inputs except the given ones as cases.

22
BASH SCRIPTING

Arrays in Bash Scripting


Arrays have an important role in programming in general. Arrays allow us to store and retrieve
elements in a list form which can be used for certain tasks. In Bash, we can also have arrays that
help us in creating scripts in the command line for storing data in a list format. While creating an
array in Bash scripting, we have several options. One of the option is by using ‘declare -a’
command before naming the array itself. One of another option is by manually assigning
elements to array. Let’s take a look at both ways in the example.

Creating and Printing Array


In this script, there are couple of arrays
defined via different ways. Let’s break it
down one by one. In the first two arrays
defined by using ‘declare -a’ command.
‘-a’ parameter is needed when we would
like to define array. In the second array,
my_list2 , the order of elements is
declared manually. The way third array,
my_list3 , defined is done by hand, row
by row. The last array, my_array , is
defined similar to defining a variable, just write the elements inside of the parentheses.

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.

As you can see, the ‘[1]’ printed the second


element inside of the array. The ‘[-1]’ printed the
last element inside of the array. The ‘[*]’ and
‘[@]’ printed all of the elements inside of the
array.

23
BASH SCRIPTING

Iterating Elements Over Array


To perform iteration operations over an array, we can use loops. Let’s see it as an example.

As you can see, we have used ‘for’ loop to print the


elements of the array. The ‘${my_array[@]}’
expands into all the elements in the array and the
‘for’ loop iterates over them one by one with the
iterator, in this case it’s ‘i’, but we can use something
different.

As you can see, the ‘for’ loop printed all of the elements of
‘my_array’.

Printing Array Indices


To print the indices of the array, we can use loops again. It will be useful when we want to print
the index of each element. Let’s create a script.

As you can see, we used ‘for’ loop again.


Maybe you could see that there is an
exclamation mark (!) at the beginning of
‘${!my_array[@]}’. This indicates that we
are accessing the indices of the array and not
the elements of the array themselves.

The ‘for’ loop returned the index number of each element by


order. If you want your output to look better, start counting
from one, you can assign a new variable to one and increase
it on each loop.

24
BASH SCRIPTING

Things to Pay Attention in Bash Scripting


1. The Shebang line is important. If Shebang line wasn’t specified in the first line of the
script file, the interpreter used depends on the OS (Operating System) implementation
and current shell. However, there is a way to run the Bash script file even though the
Shebang line is missed. The Bash script file can be run by calling the script as an
argument. For instance, ‘bash my_bash_script_file’.
2. Don’t name the Bash script file as ‘test’. That’s because the executable ‘test’ already
exists. The ‘[Link]’ file would work anyway, but it’s better to avoid it.
3. While setting the variables inside of a Bash script file, don’t put a Dollar ($) sign before
the variable name. For example, ‘$my_var=5’ is wrong, ‘my_var=5’ is correct. Use it
when calling the variable itself.
4. Don’t put a space on either or both sides of the equal sign (=) while assigning a value to
variable. Otherwise, it will fail. For example, ‘my_var = 5’ , ‘my_var= 5’ and ‘my_var =5’
will all fail while ‘my_var=5’ work.
5. There is an alternative way to react the exit code without using it. Let’s say you want
your script to do specific tasks by using if-else statement based on the result of ‘$?’ (exit
status code). Instead of specifying like ‘if [$? -ne 0]’, you can use ‘if ! cd not_exist’. The
exclamation mark (!) represents ‘not equal.’, so the if block will be executed only if the
command fails. That brings us to same point as using ‘exit status code’, but simplified.
6. It’s important to remember the different ways to run a child command, and whether you
want the output, the return value or neither. When you want to run a command and save
the output, whether as a string or an array, you use Bash’s ‘$(command)’ syntax. For
instance, ‘my_var=$(printf “Hello world!”)’. When you want to use the return value of
a command, just use the command, or add () to run a command or pipeline in subshell.
For example, ‘if ( w | grep user | grep nmap )’.
7. Bash does not typically require curly braces ({}) for variables, but it does for arrays. So
you will notice that when you reference an array, you do so with the syntax
‘${array_name}’, but when you reference a string or number, you simply use a Dollar
sign ‘$variable_name’

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

You might also like