Shell scripting is an important part of process automation in Linux. Scripting helps you write a sequence of commands in a file and then execute them.
Introduction to the Bash Shell
The Linux command line is provided by a program called the shell. Over the years, the shell program has evolved to cater to various options.
Different users can be configured to use different shells. But most users prefer to stick with the current default shell. The default shell for many Linux distros is the GNU Bourne-Again Shell (bash). Bash is succeeded by Bourne shell (sh).
How to Create Your First Bash Script
Let’s create a simple script in bash that outputs Hello World.
Create a file named hello_world.sh
touch hello_world.sh
Write the command
#!/usr/bin/bash
echo "Hello World"
Provide execution rights
Modify the file permissions and allow execution of the script by using the command below:
chmod u+x hello_world.sh
Run the script
You can run the script in the following ways:
./hello_world.sh
# or
bash hello_world.sh
The Basic Syntax of Shell Scripting
Just like any other programming language, bash scripting follows a set of rules to create programs understandable by the computer. In this section, we will study the syntax of bash scripting.
Variables
We can define a variable by using the syntax variable_name=value. To get the value of the variable, add $ before the variable.
#!/bin/bash
# A simple variable example
greeting=Hello
name=Tux
echo $greeting $name # Hello Tux
echo '$greeting $name' # $greeting $name
echo "$greeting $name" # Hello Tux
Arithmetic Expressions
Numerical expressions can also be calculated and stored in a variable using the syntax below:
#!/bin/bash
var=$((3+9))
echo $var
# Fractions
echo "scale=2;22/7" | bc
Read input
In bash, we can take user input using the read command. To prompt the user with a custom message, use the -p flag.
#!/bin/bash
echo "Enter a numner"
read a
read -p "Enter a numner" b
var=$((a+b))
echo $var
Numeric Comparison operators
Comparison is used to check if statements evaluate to true or false. We can use the below shown operators to compare two statements: