Bash Scripting – Introduction to Bash | What is Bash Scripting

introduction-to-bash-scripting
  • Save

In this blog, I will tell you about the importance of bash scripting in a programmer’s life. I will tell you about bash scripting, such as, what it is and what its advantages and disadvantages are. So let’s get started.

Table of Contents

Before learning about bash scripting, at least we should learn about what scripting is and Why it is necessary in the project. So let’s get started with the scripting.

Introduction to Scripting

You can write a series of commands in a file and execute them with the help of scripting.

It saves you a lot of valuable time because you don’t have to write certain commands again and again. Daily tasks can be completed efficiently, and they can even be scheduled for automated completion.

Additionally, you can configure some scripts to run at startup, such as those that display a specific message when a new session is started or modify the environment.

The architecture of Operating System
  • Save
The Architecture of the Operating System

A) Kernel

The kernel is the foundation of the operating system. It helps establish communication between hardware and software.

It allows the necessary abstraction for system low-level hardware or application program details to be hidden.

B) Shell

Shell serves as the user’s and the kernel’s interface. It hides from users its complexity accepts user commands and carries out kernel operations.

The operating system is categorized into two different kernel themes:

a) Graphical shells.

b) Command-line shells.

The graphical-line shell uses the graphical user interface, while the command-line shell uses the command-line interface. Both shells implement operations.

However, the graphical-line shells work slower than the command-line shells.

Introduction to Bash Scripting

BASH, a play on words that pays homage to Bourne Shell, stands for Bourne Again Shell (i.e., invented by Steven Bourne).

Bash scripting is a text-based command line interpreter that lets users interpret commands to do various tasks. It normally runs in a text window. A shell script is a collection of these commands that are contained within a file. A shell script can contain commands that Bash can read and execute.

Bash scripting is a great way to automate different types of tasks in the system. Developers can avoid doing repetitive tasks using bash scripting.

Features of Bash Scripting

Bash scripting, also known as shell scripting, involves writing scripts using the Bash (Bourne-Again SHell) language, a command-line interpreter for Unix-like operating systems. Here are key features and elements of Bash scripting:

A) Comments:

Use the # symbol to add comments to your script. Comments are ignored by the interpreter and are for human readability.

# This is a comment

B) Shebang (#!):

The shebang (#!/bin/bash) at the beginning of the script tells the system which interpreter to use to execute the script.

#!/bin/bash

C) Variables:

Use variables to store values that can be referenced or modified throughout the script. Variables are typically assigned using the equals sign =.

variable_name="value"

D) Echo: The echo command is used to print text or variable values to the standard output.

echo "Hello, world!"

E) Input/Output: Use read to read user input and display output using echo.

echo "Enter your name:"
read name
echo "Hello, $name!"

F) Conditionals (if/elif/else): Use conditionals to execute different code blocks based on conditions.

if [ condition ]; then
    # code to execute if the condition is true
elif [ another_condition ]; then
    # code to execute if another condition is true
else
    # code to execute if all conditions are false
fi

G) Functions: Define functions to group and reuse blocks of code.

function my_function() {
    echo "This is a function"
}

H) Input/Output Redirection: Use > for output redirection and < for input redirection.

echo "This is some text" > output.txt

I) Pipes (|): Use pipes to send the output of one command as the input to another.

command1 | command2

J) Error Handling: Use trap to define actions to be taken if a signal is received.

trap 'echo "Error occurred"; exit 1' ERR

These are fundamental features of Bash scripting, but there’s a lot more to learn and explore as you become more proficient in writing Bash scripts.

Application of Bash Scripting

  1. Manipulating Files.
  2. Automation of tasks.
  3. Execution of routine tasks like backup operations, checking the log files, etc.

Advantages of Bash Scripting

Bash scripting, or shell scripting using Bash (Bourne-Again Shell), offers several advantages for various use cases and system administration tasks:

A) Automation:

Bash scripting allows the automation of repetitive tasks, saving time and effort. Tasks that involve a sequence of commands or operations can be scripted to run automatically with a single script execution.

B) Customization:

Scripts can be tailored to specific requirements, enabling customization based on the needs of the user or system. Variables, conditions, and loops provide flexibility in creating versatile scripts.

C) Ease of Learning and Use:

Bash scripting has a relatively simple and intuitive syntax, making it accessible to both beginners and experienced users. The command-line interface and straightforward constructs contribute to the ease of learning and using Bash scripting.

D) Interoperability:

Bash scripts can interact with a wide range of system tools, utilities, and programs. They can call other scripts, executables, or commands written in different languages, promoting interoperability and integration within a system.

E) Cost-Effective Solution:

Bash scripting is a cost-effective solution for automation and system administration tasks. It allows organizations to create and maintain efficient processes without the need for complex software or licensing costs.

F) Portability:

Bash is the default shell for many Unix-like operating systems, including Linux. Scripts written in Bash can typically run on different systems without significant modifications, enhancing portability and ease of deployment.

G) Task Automation and Scheduling:

Bash scripts can automate tasks such as backups, data processing, file management, and more. Scheduling these scripts with tools like cron allows for automatic execution at specified times or intervals.

H) Error Handling and Logging:

Bash scripting provides options for error handling and logging, allowing scripts to detect errors, handle exceptions, and log important information for troubleshooting and auditing purposes.

By leveraging these advantages, Bash scripting can greatly enhance productivity, efficiency, and maintainability in system administration and automation tasks.

Disadvantages of Bash Scripting

While Bash scripting offers numerous advantages, it also has some disadvantages and considerations that should be taken into account:

A) Limited Performance for Intensive Tasks:

Bash scripting may not be suitable for highly intensive or compute-heavy tasks. Other compiled languages like C or Python tend to perform better for these types of tasks due to their compiled nature.

B) Limited Cross-Platform Support:

While Bash is available on many Unix-like operating systems, it may not be available or fully compatible with Windows. This limits the portability of Bash scripts and makes them less suitable for cross-platform applications.

C) Error Handling Complexity:

Error handling in Bash scripts can be more complex and error-prone compared to some other programming languages. Ensuring robust error handling requires careful consideration and testing.

D) Limited Data Structures and Functions:

Bash has limited support for complex data structures and functions compared to other programming languages. This can make it less suitable for certain types of applications that require extensive data manipulation or advanced algorithms.

E) Debugging Challenges:

Debugging Bash scripts, especially larger and more complex ones, can be challenging. Identifying and fixing errors or bugs can take more time due to the nature of shell scripting.

F) Security Risks:

Poorly written or insecurely configured Bash scripts can pose security risks, especially when dealing with sensitive information. Inadequate handling of user input or improper permissions can lead to vulnerabilities.

It’s important to weigh these disadvantages against the advantages and consider the specific use case when choosing Bash scripting or another programming language for a particular task. In many cases, the advantages of Bash scripting outweigh the disadvantages, particularly for system administration and automation tasks on Unix-like systems.

Types of Shells in Bash Scripting

There are different types of shells that are available in the Linux Operating System. Among them are the following:

  1. Bourne Shell.
  2. C shell.
  3. Korn Shell.
  4. GNU Bourne Shell.

If you want to see which shells your operating system supports, use the following command in the terminal:

$ cat /etc/shells
$ cat /etc/shells

# /etc/shells: valid login shells
/bin/sh
/bin/bash
/usr/bin/bash
/bin/rbash
/usr/bin/rbash
/bin/dash
/usr/bin/dash
/usr/bin/tmux

Use the following command in the terminal to see where your bash is located in OS:

$ which bash
$ which bash

/usr/bin/bash

Create and Run Your First Script File

Step 1:

To create an empty bash script, first, change the directory in which you want to save your script using the cd command.

Use the touch command to create a file in the directory and give the extension “.sh” to the file.

$ touch first.sh

Step 2:

Put your command in that .sh file now. For example, we are printing the statement “This is our first bash program”

For writing the command in the file, we have to use the nano command.

$ nano first.sh

Now, type the command or code in that file.

#!/bin/bash

echo "This is our First Bash Program"

Here, #! is called a shebang, and the rest of the line is the path to the interpreter, specifying the location of the bash shell in our operating system.

After writing the code in the file, press Ctrl+X and press Y to save the file. Now, write the command ls -l

$ ls -l
total 4
-rw-rw-r-- 1 binfintech binfintech 51 Jan 19 13:19 first.sh

Here, we don’t have permission to execute the file. Now write the command for giving the permission for executing the file. Write the command

chmod u+x file_name.sh

$ chmod u+x first.sh 

$ ls -l

total 4
-rwxrw-r-- 1 itsvek03 itsvek03 51 Jan 19 13:19 first.sh

Now you can see the extra x in -rwxrw-r–, which means that you can execute the file.

Step 3:

For executing the file, use ./file_name in the terminal.

$ ./first.sh 
This is our First Bash Program

Now, you can see the output of the script file.

A) SheBang(#!)

The She Bang (#!) is a character sequence that consists of the character’s number sign (#) and exclamation mark (!) at the beginning of the script.

When a script with a shebang is launched as a program under Unix-like operating systems, the program loader interprets the rest of the lines after the first line as an interpreter directive.

The route directive for the execution of many types of scripts, such as Bash, Python, etc., is known as SheBang, which denotes an interpreter to run the script lines.

#!/bin/bash

The formatting of the shebang is most important. Its wrong format may result in commands not functioning properly. Therefore, keep in mind the following two SheBang formatting principles whenever you’re writing a script:

  1. It should always be on the very first line of the Script.
  2. There should not be any space before the hash (#), between the hash exclamation marks(#!), and the path to the interpreter.

B) echo

  1. In Bash, the built-in command echo is used to show the standard output while supplying inputs.
  2. It is the command that is used the most frequently to print lines of text or a String to the screen.
  3. Both Bash Shell and Command Line Terminal platforms give it the same performance.

Syntax:

echo [option] [string]
echo [string]

C) Comments in Bash Scripting

  1. It is one of the important parts of the programming language. It helps the programmer with the use of any code or function.
  2. Comments are the strings that help in the readability of the program.
  3. They are not executed when we execute the commands in the Bash Scripts file.

Bash scripting supports two types of comments, which are as follows:

  1. Single Line Comment
  2. Multi-line Comment

a) Single Line Comment

To write single-line comments in bash scripting, we have to use the hash (#) symbol at the start of the comment.

#!/bin/bash

# This is the single line comment

echo "This is the comment of the Bash Scripting"

##Output:
This is the comment of the Bash Scripting

b) Multi-Line Comment

To insert multi-line comments, there are two ways:

  1. We can write multi-line comments in bash scripting by enclosing the comments between <<COMMENT and COMMENT.
  2. By enclosing the comments between (:’) and a single quote (‘).

#!/bin/bash

<<COMMENTS
This is the first line comment
This is the second line comment
This is the third line comment
COMMENTS

echo "This was the first type"


: '

This is the first line comment
This is the first line comment
'

echo "This was the second type"

## Output:

This was the first type.

This was the second type.

CheatSheet for Learning Bash Scripting

For learning commands in bash follow the cheat sheet

FAQ

What is Bash Scripting?

Bash scripting is a text-based command line interpreter that lets users interpret commands to do various tasks.

Is bash easier than Python?

Python is a high-level programming language that is intended to be simple to learn and use. While Bash is an interpreter for the sh command language, it can also execute instructions taken from files or standard input.
Python is easier than Bash. because Python is easier to maintain.

Why bash is used?

Bash scripting is a great way to automate different types of tasks in the system. Developers can avoid doing repetitive tasks by using a bash script.

How do I execute the bash script file?

1) Create the file by using the command touch file_name.sh.

2) Now, write the command in that file
nano file_name.sh

Write the command.
Ctrl+X and Press Y

3) Now for giving permission to execute the file
chmod u+x file_name.sh

4) Now run the file
./file_name.sh

Recent Articles on Linux Operating System

  1. Directory in Linux Define | Linux Directory & its Commands
  2. Explain the chmod command in Linux | Linux chmod command
  3. Linux User Management || User Management in Linux
  4. Linux Computer Network Advanced Command | Network Command
  5. Redirection in Linux I/O| Linux I/O Redirection
  6. CronTab and Job Scheduling in Linux | Make CronTab Project
  7. Linux Firewall Unlock Rules with Firewall-cmd Tutorial
  8. netstat command in Linux | Linux netstat command
  9. SSH Command Full Guide with Practical | Linux SSH Service
  10. awk command Guide | How to arrange the output of the file in Linux
  11. sed command Full Guide Tutorial | Linux sed Command
  12. Iptables commands Full Guide: How to make our own Firewall

Recent Articles on Computer Networks

  1. Introduction to Computer Networking | What is Computer Network
  2. What are Topology & Types of Topology in Computer Network
  3. What is FootPrinting in Cyber Security and its Types, Purpose
  4. Introduction to Cloud Computing | What is Cloud Computing
  5. Distributed Shared Memory and Its Advantages and Disadvantages
  6. What is a VPN? How does a VPN Work? What VPN should I use?
  7. What is an Internet and How the Internet Works
  8. What is a Website and How Does a Website or web work?
  9. Introduction to Virus and Different Types of Viruses in Computer
  10. What is TCP and its Types and What is TCP three-way Handshake
  11. What is the UDP Protocol? How does it work and what are its advantages?
  12. What is an IP and its Functions, What is IPv4 and IPv6 Address
  13. What is MAC Address and its Types and Difference MAC vs IP
  14. What is ARP and its Types? How Does it Work and ARP Format
  15. Sessions and Cookies and the Difference Between Them
  16. What is ICMP Protocol and its Message Format?
  17. What is Big Data? Characteristics and Types of Big Data
  18. Disciplines of CyberSecurity | What are the goals of CyberSecurity?
  19. What is Firewall, Features, Types and How does the Firewall Work?
  20. Network Scanning, Types, and Stealth Scan in Computer Network
  21. Cryptography and its Types in Ethical Hacking
  22. Tor Browser and How Does It Work | Onion Router Tutorial
  23. Proxy Server, Advantages, Difference between Proxy Server & VPN
  24. DHCP Protocol and What Are the Pros and Cons of DHCP
  25. Intrusion Detection System(IDS) and What are the types of IDS
  26. Domain Name Server, How Does It Work, and its advantages
  27. Telnet: Introduction, How Does it Work, and Its Pros and Cons
  28. SOC: Introduction, Functions performed by SOC, and its Pros
  29. What is SIEM? | What is the Difference between SIEM and SOC?
  30. Application Layer in OSI Model | OSI Model Application Layer
  31. What is SSL Protocol or SSL/TLS and SSL Handshake, and Architecture of SSL
  32. What are Servers, how do they work, and its different Types
  33. Network Devices-Router, Switch, Hub, etc in Computer Network
  34. Connection Oriented and Connection-less Services in Network
  35. Physical Layer in OSI Model | OSI Model Physical Layer
  36. Presentation Layer in OSI Model | OSI Model Presentation Layer
  37. Session layer in OSI Model | OSI Model Session layer
  38. Transport Layer in OSI Model | Computer Network Transport Layer
  39. Network Layer in OSI Model | OSI Model Network Layer
  40. Data Link Layer in OSI Model | OSI Model Data Link Layer
  41. Block Diagram of Communication System with Detailed Explanation
Write blogs related to Ethical hacking, Computer networks, Linux, Penetration testing and Web3 Security.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top
0 Shares
Share via
Copy link