linux terminal with sudo
Tue Oct 25

Bash Scripting for Beginners

As Linux users, it is more likely for you to be familiar with the terms bash and shell. Many perceive the two are the same thing. Basically, the shell is a command interpreter that connects the user with the operating system (the kernel to be more accurate). On the other hand, Bash Is a kind of shell as well as zsh, csh, fish.

Why learn bash scripting?

In spite of being frequent users, many don’t realize how powerful this thing is. By mastering Linux commands, you can easily perform any system administration even without using a GUI (Graphic User Interface). By learning bash scripting, doing tedious and cumbersome tasks will be the problem of the past. From managing files and directories to automating tasks will be much easier by automating it using script.

Using its ability to interact directly with the kernel, it does not really require dependencies or modules unlike other programming languages. Furthermore, you could literally take control of the entire system by escalating permission and privilege. Of course, the act could be disastrous when it was done by the wrongdoers.

Managing executable attribute

The extension you will use is .sh. You can use vim or nano if you want to do everything on the terminal. However, using any text-editor is okay. Before starting, make sure to make your script executable. To do this, you can use the command

$ chmod 744 <filename> or chmod +x <filename>

If you wonder what chmod and what 744 is, check my previous writing here. The +x is needed to give the file executable attribute. To revoke this, simply change it to -x.

The first thing you need to do is type this, you need to add

#!/bin/bash

on the top of your script. In short, this is called a shebang which refers to the interpreter you will use.

When you have done scripting, save it and you can execute your script by using the command

$ ./script_name.sh.

Getting started

Variable

Variable is a named storage used to store information. Some rules that are related to variable.

  1. Do not use space before and after equal sign
  2. Use $ to use variable
  3. Use “ ” for string
  4. Use ${variable} to join with string
  5. Use ${UPPER_CASE} to define environment variable, and ${lower_case} for local variable

Example

#!/bin/bash

#use echo to print text
number=12 #example 1
echo "The number is $number" #example 2

sport="basket" #example 3
echo "I love playing ${sport}ball" #example 4

echo "$HOME" #example 5

User input

There is a time we want to process user input. You can use read command to do this. Read command is often followed by -p flag to use prompt. When you use read command, you can give name for each input data. Let’s say your name is John Doe. By using example 2, you can take both variable as different values.

Example

#!/bin/bash

#Example 1
read -p "What is your name? " name
echo "Your name is ${name}"

#or

echo "What is your name? "
read name
echo "Your name is ${name}"

#Example 2
echo "What is your name? "
read fname lname
echo "Your name is ${fname} ${lname}"

Conditional if else

Most of the time you want to do some task based on the conditional you set. As well as any programming language, you can execute task based on predefined condition.

Syntax

if [ condition ]
then
	#Do task if condition is true
else
	#Do task if condition is false
fi

Example

#!/bin/bash

if [ -e ./ok.txt ]
then
	echo "File exists."
else
	echo "File doesn't exist."
fi

The code above will check whether the file exist or not on the current directory. You may wondering, what does -e means in a condition. The -e flag based on test command to check file existence. You can change it to -d to check if directory with certain name exist or not in the current directory. The script is equivalent with this command.

$ test -e ./ok.txt && echo "File exists." || echo "File doesn't exist."

For reference, use below command on the terminal.

$ man test

Looping

In bash, we can use three different methods of looping.

For Loop

For loop is used for running repetitive task based on the list.

Syntax

list="var1 var2 var3" #optional

for variable in ${list}
do
	echo "${variable}"
done

Example

#!/bin/bash

# Iterating from list
names="Tom John Julia" #optional

for name in ${names}
do
	echo "Hello ${name}"
done

#or you can iterate from file
for name in ${cat names.txt}
do
	echo "Hello ${name}"
done

While Loop

Syntax

while [condition is true]
do
	#do task
done

Example

#!/bin/bash

num=10
while [[ $num -gt 0 ]]
do
 	echo "num = $num"
		((num--))
 		sleep 1
done

Until loop

Syntax

until [condition is false]
do
	#do task
done

Example

#!/bin/bash

num=10
until [[ $num -lt 0 ]]
do
 	echo "num = $num"
		((num--))
 		sleep 1
done

Using pretty similar example, it would be easier to differentiate between the two. On the while and until loop example above, you can see in what condition both needs to be fulfilled. The flag -gt means “greater than” and -lt means “less than”. Sleep is only used to make it easier to read the output in a sequence of 1 second. In while loop, the code will WHILE the conditions is met. In until loop, the code will be executed UNTIL the condition is no longer met. Otherwise, you can check both code on your own the terminal.

Function

Function is really useful as you make more complex script. By using function, you can run sets of code over and over whenever you need it just by declaring it. It is always recommended to let single function to do the single task as well. There are two ways of using function in bash scripting which you can use based on your personal preference. Without calling the function, your script won’t work.

Syntax

function function_name(){
	#sets of code to execute
}

#or you can also use
function_name(){
	#sets of code
}

#to call the function. you can use
function_name

Example

#!/bin/bash

function hello(){
	echo "Hello world"
}

hello

Conclusion

In fact, there are so much more topic to learn about bash scripting. As you delve deeper, you might find some topics that are not covered here like special parameters, positional parameters, using select, case and so on which I would like to cover more in the future.