Start Your Scripting Journey Today | Bash Script — Part 1

Everything You Need to Know to Write Bash Scripts

Md Shamim
Level Up Coding

--

Photo by Ty Sugg on Unsplash

Your first script

A Bash script is a plain text file that contains a series of commands. Anything we can normally run from the command line can be used to create a script.

The first line of a bash script:

#!/bin/bash

The hash and exclamation mark ( #! ) character sequence is referred to as the Shebang. Followed by “/bin/bash” which is the path to the interpreter that should be used to run the rest of the commands.

Let’s create our first bash script :

Execution process:
We can execute a script using the relative path and the absolute path. And before executing a script, we need to make the script executable using the chmod command :

$ chmod +x fisrtscript.sh  # Make the script executable
$ ./firstscript.sh # Executing the script (using relative path)
-------------------------------------
Hello Learners!

In the bash script, anything after the “#” will be assumed as comments.

Task — 1

Suppose, we need to install an apache webserver, and then we have to deploy a simple static webpage into the webserver. Since the static webpage is stored in GitHub, we have to clone the corresponding git repository into the webserver’s default directory.

As we discussed earlier, a bash script is a collection of commands. Let’s try to achieve our goal by creating a script;

Execute the above script:

$ chmod +x webserver-setup.sh 
$ ./webserver-setup.sh

Now, let's check if the apache webserver is serving our static website or not :

curl http://18.181.179.198/

Variables

A variable is nothing but a pointer to the actual data. The shell enables us to create, assign, and delete variables. A variable can be created in the following way :

GREET=”Hello, World”
echo $GREET

To concatenate a variable with a string, we have to use curl { } brackets. Example —

TIME=12
DAY=”Monday”

echo “It’s ${TIME}pm, $DAY”

Task — 2

Create a script with several variables, and assign diverse types of data to those variables.

# Execute the script
$ chmod +x variables.sh
$
./variables.sh
----------------------------
Hello, World
It's 12pm, Monday
Money exchange rate:
USD TO YEN: 1$ = 144.7655¥

Command line arguments

A command line argument is a parameter that we can provide to our bash script during execution.

To pass an argument to your Bash script, we just need to write it after the name of our bash script while executing it;

./script.sh <argument> <argument>

The first argument will be stored in $1, the second in $2, and the third in $3…..$9. We can use $1 to $9 to store command line arguments.

echo “Your favourite TV series is: $1”
echo “Your favourite movie is: $2”

Task — 3

Modify the above script a little bit with command line arguments.

# Execute the script with arguments
$
chmod +x command-line-args.sh
$ ./command-line-args.sh 12 monday 1 144.23
--------------------------------------------------------------------
Hello, World
It's 12pm, monday
Money exchange rate:
USD TO YEN: 1$ = 144.23¥

Special and Reserved variables

Following is the list of some special variables :

$0 — The filename of the current script.
$1-$9 — Stores the names of the first 9 argument
$$ — The process id of the current bash.
$# — The number of arguments supplied to a script.
$* — Stores all the command line arguments by joining them together.
$@ — Stores the list of arguments as an array.
$? — Specifies the exit status of the last command or the most recent execution process.

Following is the list of some reserved variables :

HOSTTYPE — The name of the current host.
HOSTNAME — Generates a random integer between 0 and 32767.
PWD — Returns The current working directory.
OSTYPE — return operating system Bash is running on.

More about special and reserved variables from here.

TASK — 4

Create a script by using some special and reserved variables.

# Execute the script
$
chmod +x special.sh
$ ./special.sh
--------------------------------------------------------------------
Welcome to TASK-3
Environment configuration:
OSTYPE: linux-gnu
HOSTTYPE: x86_64
HOSTNAME: centos
Script details:
Script name: ./special.sh
Process Id: 8940

Environment variables

Pre-defined env
There are many pre-defined env variables available in the system. To find out all the pre-defined env variables use printenv command.

$ printenv--------------------
XDG_SESSION_ID=163
HOSTNAME=centos
TERM=xterm
SHELL=/bin/bash
--------------------
$ echo $SHELL
/bin/bash
$ echo $HOSTNAME
centos

Create a new env variable
We can create a new env variable in Linux using the export command :

$ export APP_MODE="test"

The above-created environment variable can be used in the bash scripts :

echo “Current app mode is: $APP_MODE”

The env variable will not be persistent, if we close our terminal, restart the server, or the session ends.

To permanently persist the env variables, there are two ways: we can persist env variables only for the corresponding user or for all the users.

To persist env variables only for the corresponding user, we have to put our env variable under the .bashrc file located in the user's home directory.

# Add env into the .bashrc
$ echo "export APP_MODE=test" >> ~/.bashrc
# Reload the file
$ source ~/.bashrc
$ echo $APP_MODE
----------------
test

To persist env variables for all the users we have to put our env variable under /etc/profile file.

# Add env into the /etc/profile file
$ su
$ vim echo "export APP_VERSION=1.25.0" >> /etc/profile
# Reload the file
$ source /etc/profile
$ echo $APP_VERSION
-------------------
1.25.0

Task — 5

Use the above-created env variables to a script:

# Execute the script
$
chmod +x env.sh
$
./env.sh
--------------------------------------------------------------------Current app mode is: test
Current app version is: 1.25.0

Command Substitution

Command substitution in Bash allows us to execute a command and substitute it with its standard output.

Note: This command executes within a subshell, which means it has its own environment and so it will not affect the parent shell’s environment.

# Execute the script
$
chmod +x command-sub.sh
$ ./command-sub.sh
----------------------------------------
Mon Oct 3 09:02:21 UTC 2022
----------------------------------------
Available space in 'dev' disk: /dev 474M
Used Memory: 295M

Quotes

We can use both the single or double quotes in a bash script. But use cases of the single quotes and doubles quotes are different:

# Double quotes
$ echo "hostname is: $HOSTNAME"
--------------------------------
hostname is: centos
--------------------------------
# Single quotes
$
echo 'hostname is: $HOSTNAME'
--------------------------------
hostname is: $HOSTNAME
--------------------------------

Single quotes ignore all the special characters (such as — $ & * ; |.') and print the statement as it is.

In contrast, To print a special character within the double quotes we have to use a backward slash ( \ ) in front of the character we want to print.


$ echo "hostname is:\"$HOSTNAME\""
--------------------------------
hostname is: "centos"
$ echo "I have only 5\$ today"
--------------------------------
I have only 5$ today

User Input

To create an interactive script, we may need to get inputs from the users. using the read command we can get inputs from the users.

When NAME is not specified, a variable named REPLY is used to store user input.

$ read 
$ echo $REPLY

Read and Insert into a variable:

$ read $VAR
$ echo $VAR

We can use various options while reading data.

-p promt user with some message
-s promt user for a secret
-n limit the number of character limit using

Task — 6

Create a script, where you need to read data from the users and try to use special characters within the double quotes.

# Execute the script
$
chmod +x userlogin.sh
$ ./userlogin.sh
----------------------------------------
Welcome to "kubehub.com"
USENAME: shamim
Enter your 4 digit PIN
PIN:
Successfully singed in
Welcome, shamim

Difference between $( ) and ${ } in Bash

During the command substitution, we have to use $(command).
On the other side, we can use ${paramtere} to avoid ambiguity.

# command substitution $()
$ USED_MEM=$(free -m | grep Mem | awk '{print $3}')
# without using ${}
$ echo $USED_MEMMB
------------------------
No output, because there is no variable named "USED_MEMMB"
# by using ${}
$ echo ${USED_MEM}MB
-------------------------
295MB

If you found this article helpful, please don’t forget to hit the Follow and Clap buttons to help me write more articles like this.
Thank You 🖤

--

--

Cloud Infrastructure Engineer | AWS Community Builder | AWS | Kubernetes | GitHub Actions | Terraform | 👇👉 linkedin.com/in/shamimice03 github.com/shamimice03