~By AbhinayBash Commands

title image

Definition of Bash scripting

A bash script is a file containing a sequence of commands that are executed by the bash program line by line. It allows you to perform a series of actions, such as navigating to a specific directory, creating a folder, and launching a process using the command line.

By saving these commands in a script, you can repeat the same sequence of steps multiple times and execute them by running the script.

Advantages of Bash scripting

Bash scripting is a powerful and versatile tool for automating system administration tasks, managing system resources, and performing other routine tasks in Unix/Linux systems. Some advantages of shell scripting are:

  • Automation: Shell scripts allow you 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 through the use of emulators or virtual machines.
  • Flexibility: Shell scripts are highly customizable and can be easily modified to suit specific requirements. They can also be combined with other programming languages or utilities to create more powerful scripts.
  • Accessibility: Shell scripts are easy to write and don't require any special tools or software. They can be edited using any text editor, and most operating systems have a built-in shell interpreter.
  • Integration: Shell scripts can be integrated with other tools and applications, such as databases, web servers, and cloud services, allowing for more complex automation and system management tasks.
  • 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.

Overview of Bash shell and command line interface

The terms "shell" and "bash" are used interchangeably. But there is a subtle difference between the two.

The term "shell" refers to a program that provides a command-line interface for interacting with an operating system. Bash (Bourne-Again SHell) is one of the most commonly used Unix/Linux shells and is the default shell in many Linux distributions.


The shell accepts commands from the user and displays the output


f the shell is running as root (a user with administrative rights), the prompt is changed to #. The superuser shell prompt looks like this:

[root@host ~]#

Although Bash is a type of shell, there are other shells available as well, such as Korn shell (ksh), C shell (csh), and Z shell (zsh). Each shell has its own syntax and set of features, but they all share the common purpose of providing a command-line interface for interacting with the operating system.

You can determine your shell type using the ps command: ps

In summary, while "shell" is a broad term that refers to any program that provides a command-line interface, "Bash" is a specific type of shell that is widely used in Unix/Linux systems.

Let's discuss a few basic bash commands and see their outputs. Make sure to follow along :)

  • date: Displays the current date

zaira@Zaira:~/shell-tutorial$ date
Tue Mar 14 13:08:57 PKT 2023

  • pwd: Displays the present working directory.

zaira@Zaira:~/shell-tutorial$ pwd
/home/zaira/shell-tutorial

  • ls: Lists the contents of the current directory.

zaira@Zaira:~/shell-tutorial$ ls
check_plaindrome.sh count_odd.sh env log temp

  • echo: Prints a string of text, or value of a variable to the terminal.

zaira@Zaira:~/shell-tutorial$ echo "Hello bash"
Hello bash

You can always refer to a commands manual with the man command.

How to Create and Execute Bash scripts

Script naming conventions

By naming convention, bash scripts end with .sh. However, bash scripts can run perfectly fine without the sh extension.

Adding the Shebang

Bash scripts start with a shebang. Shebang is a combination of bash # and bang ! followed by the bash shell path. This is the first line of the script. Shebang tells the shell to execute it via bash shell. Shebang is simply an absolute path to the bash interpreter.

Below is an example of the shebang statement.

#!/bin/bash

You can find your bash shell path (which may vary from the above) using the command:

which bash

Creating our first bash script

Our first script prompts the user to enter a path. In return, its contents will be listed.

Create a file named run_all.sh using the vi command. You can use any editor of your choice.

vi run_all.sh

Add the following commands in your file and save it:

#!/bin/bash
echo "Today is " `date`

echo -e "\nenter the path to directory"
read the_path

echo -e "\n you path has the following files and folders: "
ls $the_path

Let's take a deeper look at the script line by line. I am displaying the same script again, but this time with line numbers.

1 #!/bin/bash
2 echo "Today is " `date`
3
4 echo -e "\nenter the path to directory"
5 read the_path
6
7 echo -e "\n you path has the following files and folders: "
8 ls $the_path

  • Line #1: The shebang (#!/bin/bash) points toward the bash shell path.
  • Line #2: The echo command is displaying the current date and time on the terminal. Note that the date is in backticks.
  • Line #4: We want the user to enter a valid path.
  • Line #5: The read command reads the input and stores it in the variable the_path.
  • line #8: The ls command takes the variable with the stored path and displays the current files and folders.

Executing the bash script

To make the script executable, assign execution rights to your user using this command:

chmod u+x run_all.sh

Here,

  • chmod modifies the ownership of a file for the current user :u.
  • +x adds the execution rights to the current user. This means that the user who is the owner can now run the script.
  • run_all.sh is the file we wish to run.

You can run the script using any of the mentioned methods:

  • sh run_all.sh
  • bash run_all.sh
  • ./run_all.sh

Bash Scripting Basics

Comments in bash scripting

Comments start with a # in bash scripting. This means that any line that begins with a # is a comment and will be ignored by the interpreter.

Comments are very helpful in documenting the code, and it is a good practice to add them to help others understand the code.

These are examples of comments:

# This is an example comment
# Both of these lines will be ignored by the interpreter

Variables and data types in Bash

Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.

There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.

In Bash, you can use and set the variable values in the following ways:

  1. Assign the value directly:

country=Pakistan

  1. Assign the value based on the output obtained from a program or command, using command substitution. Note that $ is required to access an existing variable's value.

same_country=$country

To access the variable value, append $ to the variable name.

zaira@Zaira:~$ country=India
zaira@Zaira:~$ echo $country
India
zaira@Zaira:~$ new_country=$country
zaira@Zaira:~$ echo $new_country
India

Variable naming conventions

In Bash scripting, the following are the variable naming conventions:

Variable names should start with a letter or an underscore (_).

Variable names can contain letters, numbers, and underscores (_).

Variable names are case-sensitive.

Variable names should not contain spaces or special characters.

Use descriptive names that reflect the purpose of the variable.

Avoid using reserved keywords, such as if, then, else, fi, and so on as variable names.

Here are some examples of valid variable names in Bash:

name
count
_var
myVar
MY_VAR

And here are some examples of invalid variable names:

2ndvar (variable name starts with a number)
my var (variable name contains a space)
my-var (variable name contains a hyphen)

Following these naming conventions helps make Bash scripts more readable and easier to maintain.

Input and output in Bash scripts

Gathering input

In this section, we'll discuss some methods to provide input to our scripts.

  • Reading the user input and storing it in a variable

We can read the user input using the read command.

#!/bin/bash

echo "What's your name?"

read entered_name

echo -e "\nWelcome to bash tutorial" $entered_name

  • Reading from a file

This code reads each line from a file named input.txt and prints it to the terminal. We'll study while loops later in this article.

while read line
do
echo $line
done < input.txt

  • Reading from a file

This code reads each line from a file named input.txt and prints it to the terminal. We'll study while loops later in this article.

while read line
do
echo $line
done < input.txt

  • Command line arguments

In a bash script or function, $1 denotes the initial argument passed, $2 denotes the second argument passed, and so forth.

This script takes a name as a command-line argument and prints a personalized greeting.

echo "Hello, $1!"

We have supplied Zaira as our argument to the script.

#!/bin/bash
echo "Hello, $1!"

Displaying output

Here we'll discuss some methods to receive output from the scripts.

  • Printing to the terminal:

echo "Hello, World!"

This prints the text "Hello, World!" to the terminal.

  • Writing to a file:

echo "This is some text." > output.txt

This writes the text "This is some text." to a file named output.txt. Note that the >operator overwrites a file if it already has some content.

  • Appending to a file:

echo "More text." >> output.txt

This appends the text "More text." to the end of the file output.txt.

  • Redirecting output:

ls > files.txt

This lists the files in the current directory and writes the output to a file named files.txt. You can redirect output of any command to a file this way.

Bash commands:

  • ls - The most frequently used command in Linux to list directories
  • pwd - Print working directory command in Linux
  • cd - Linux command to navigate through directories
  • mkdir - Command used to create directories in Linux
  • mv - Move or rename files in Linux
  • cp - Similar usage as mv but for copying files in Linux
  • rm - Delete files or directories
  • touch - Create blank/empty files
  • ln - Create symbolic links (shortcuts) to other files
  • clear - Clear the terminal display
  • cat - Display file contents on the terminal
  • echo - Print any text that follows the command
  • less - Linux command to display paged outputs in the terminal
  • man - Access manual pages for all Linux commands
  • uname - Linux command to get basic information about the OS
  • whoami - Get the active username
  • tar - Command to extract and compress files in linux
  • grep - Search for a string within an output
  • head - Return the specified number of lines from the top
  • tail - Return the specified number of lines from the bottom
  • diff - Find the difference between two files
  • cmp - Allows you to check if two files are identical
  • comm - Combines the functionality of diff and cmp
  • sort - Linux command to sort the content of a file while outputting
  • export - Export environment variables in Linux
  • zip - Zip files in Linux
  • unzip - Unzip files in Linux
  • ssh - Secure Shell command in Linux
  • service - Linux command to start and stop services
  • ps - Display active processes kill and
  • killall - Kill active processes by process ID or name
  • df - Display disk filesystem information
  • mount - Mount file systems in Linux
  • chmod - Command to change file permissions
  • chown - Command for granting ownership of files or folders
  • ifconfig - Display network interfaces and IP addresses
  • traceroute - Trace all the network hops to reach the destination
  • wget - Direct download files from the internet
  • ufw - Firewall command
  • iptables - Base firewall for all other firewall utilities to interface with
  • apt, pacman, yum, rpm - Package managers depending on the distribution
  • sudo - Command to escalate privileges in Linux
  • cal - View a command-line calendar
  • alias - Create custom shortcuts for your regularly used commands
  • dd - Majorly used for creating bootable USB sticks
  • whereis - Locate the binary, source, and manual pages for a command
  • whatis - Find what a command is used for
  • top - View active processes live with their system usage
  • useradd and usermod - Add a new user or change existing user data
  • passwd - Create or update passwords for existing users

Now let’s dive a little deeper into each of these commands and understand them in more detail. We already have a lot of existing articles for each of those individual commands. For your convenience, we’ll add links to all the existing articles, and continue to update the article as new topics are covered.

Conclusion

In this article, we started with how to access the terminal and then ran some basic bash commands. We also studied what a bash shell is. We briefly looked at branching the code using loops and conditionals. Finally, we discussed automating the scripts using cron followed by some troubleshooting techniques.