Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Shell scripting is a method of automating tasks in Unix and Linux systems using a sequence of commands stored in a file. It enables users to execute multiple instructions efficiently, reducing manual work. Shell scripts are widely used for system administration, task scheduling, and automation.
In this article, we will discuss the basics of shell scripting, its advantages, and how to create and execute scripts with examples.
What is Shell Scripting?
Shell scripting is writing a series of commands in a script file to automate tasks in a Unix/Linux shell. It simplifies repetitive tasks, enhances efficiency, and allows system administration and automation.
How Does Shell Scripting Work?
Shell scripting works by automating tasks through a sequence of shell commands written in a script file. It helps in executing multiple commands at once, reducing manual intervention. Here’s how shell scripting functions in detail:
1. Writing a Shell Script
A shell script is a text file containing a list of commands.
It starts with a shebang (#!) followed by the shell interpreter (e.g., #!/bin/bash).
Commands are written just like they would be executed in the terminal.
Variables, loops, and conditions can be included to make the script dynamic.
Example Script (script.sh):
#!/bin/bash
echo "Hello, this is my first shell script!"
2. Making the Script Executable
Before executing a script, you need to grant it execution permissions:
chmod +x script.sh
3. Running the Shell Script
To execute the script, run:
./script.sh
or
bash script.sh
4. Understanding How the Shell Processes the Script
When a script is executed, the shell reads the script line by line.
It interprets each command and executes it accordingly.
If any command fails, the shell may stop execution unless error handling is implemented.
5. Features Used in Shell Scripting
Variables: Store and manipulate data.
name="John"
echo "Hello, $name"
Loops: Automate repetitive tasks.
for i in {1..5}
do
echo "Number: $i"
done
Conditional Statements: Execute commands based on conditions.
if [ -f "file.txt" ]; then
echo "File exists"
else
echo "File not found"
fi
Functions: Define reusable code blocks.
function greet() {
echo "Welcome to Shell Scripting!"
}
greet
6. Use Cases of Shell Scripting
Automating system administration tasks (e.g., backups, user management).
#!/bin/bash
set -e # Exit script if any command fails
set -o pipefail # Detect failures in pipelines
trap 'echo "Error occurred at line $LINENO"' ERR # Debugging
What is Shell?
A shell is a command-line interface that acts as an intermediary between the user and the operating system, allowing users to execute commands, run scripts, and manage system processes.
Characteristics of Shells
Some common characteristics of Shells are mentioned below. Note that it is not compulsory for Shells to check off all the characteristics.
A Shell can be made using a text editor of your preference.
A Shell program is executed similarly to Shell commands. You only need to type the program's name along with the Enter key.
A Shell program is a simple program consisting of primitive Shell commands.
Shell programs are in free format. That means a program is correct if its shell commands follow the syntax. You can use blank lines, indentation, and whitespace freely.
Like any other program, shell programs allow input and output, logical decision-making, file creation and deletion, and system calls.
Shell programs have permission modes similar to any other file. You must have correct permissions set for program execution.
Types of Shells
Several types of shells are available, and they are listed below.
Bourne Shell
Bash Shell
C Shell
TENEX Shell
Korn Shell
Z Shell
Fish Shell
In this article, we will focus mainly on the Bash Shell. This is because it is the standard shell that is intuitive and flexible. It is the default shell of many Linux distributions today. It is very well compatible with other shell types and carries many improvements over previous shell types. These improvements include Command-line editing, Job Control, infinite-size command history, etc.
Important Commands
echo
It simply prints the line of text. It is similar to the ‘println’ keyword of Java.
file
It returns the type of script file.
type
It displays how the shell command’s arguments will be interpreted. That means whether the commands used will be read-only, write-only, read-write only, or read-write-executable.
whereis
It tells you the location of the source image, executable file, and manual pages of any shell command.
which
It is used to specify the file to be used for any shell script. You need to mention a particular file name here.
Starting with Shell Scripting
Pre-preparation
1. To start with Shell Scripting, open the terminal using the desktop icon or the shortcut key ‘Ctrl+Alt+T’.
2. Now, check the shell types your Operating System supports. Use the command ‘cat /etc/shells’ for the same and press enter. You will see a list of shells your operating system supports.
3. In this article, we are using Bash Shell. So, to know the location of this Bash Shell, use the ‘which bash’ command and press enter.
We have completed all the pre-preparation parts.
Creating a Shell File
We will clear the screen for a fresh start. To create a shell file, follow these steps.
1. Navigate to the Desktop folder or directory. Use the command in the image below.
2. Create a new shell script file in that directory, ‘hello.sh’. We will use the ‘touch’ mode for the same. Note that ‘.sh’ extension is not necessary for execution. We have used it here to differentiate a shell file from other files. It is considered a good practice to use this extension. Also, the ‘touch’ mode provides only read and write permissions. Use the command in the image below.
3. Please enter to create the ‘hello.sh’ file finally.
You will see a ‘hello.sh’ file on your desktop.
Creating a Shell Script
Now, we will create our first and very simple shell program. This bash shell program will print ‘Hello World’. Use the following steps for the proper execution. Note that you can use any editor of your choice. Double-click on the shell file to open the default editor. Here, we will use Visual Studio Code as our editor. We will use the ‘code .’ command to open the previously created shell file in Visual Studio Code.
1. Open the editor and see the directory you imported using the above command. You will see an empty shell script.
2. Use the command in the image below for proper execution.
3. Save the command and minimize the editor.
4. Execute the shell script in the terminal. It shows permission denied. It is because of the ‘touch’ mode we used.
5. We will update the script’s permissions by adding ‘chmod’ mode. It will add ‘execute’ permission to the shell file.
6. We will execute the script again. It prints ‘Hello World’.
You have now written your first successful shell script.
Advantages of Shell Scripting
Automation of Tasks – Reduces manual effort by automating repetitive system tasks like backups, file management, and user administration.
Ease of Use – Simple to write and execute compared to other programming languages. Shell commands are straightforward and easy to learn.
Efficiency – Speeds up processes by executing multiple commands in sequence without user intervention.
Flexibility – Works on different Unix/Linux-based systems without major modifications.
Integration with System Commands – Directly interacts with system utilities and commands, making it ideal for system administration.
Minimal Resource Usage – Shell scripts consume fewer system resources compared to GUI-based automation tools.
Customizability – Easily modified and extended to suit different user requirements.
Quick Prototyping – Useful for testing commands and logic before implementing them in full-fledged programming languages.
Disadvantages of Shell Scripting
Platform Dependency – Scripts written for one shell (e.g., Bash) may not work in another (e.g., Zsh) without modifications.
Error Handling Complexity – Debugging shell scripts can be difficult as they lack advanced error-handling mechanisms.
Limited Performance – Slower than compiled languages like C or Java, especially for large and complex tasks.
Security Risks – Improperly written scripts can expose system vulnerabilities or execute harmful commands accidentally.
Lack of Advanced Features – Does not support modern programming features like object-oriented programming (OOP) or strong data structures.
Difficult to Maintain – As scripts grow in complexity, maintaining and debugging them becomes challenging.
Limited Portability – Scripts may behave differently across various Unix/Linux distributions due to shell version differences.
Frequently Asked Questions
What is the first line in a shell script?
The first line in a shell script is the shebang (#!) followed by the interpreter path (e.g., #!/bin/bash), which tells the system which shell to use.
Why do we need shell scripting?
Shell scripting automates repetitive tasks, manages system operations, performs batch processing, and enhances efficiency by executing multiple commands in sequence without manual intervention.
How to use symbols in shell scripts?
Symbols like $ (variable reference), # (comment), > (redirection), | (pipe), and & (background execution) are used to control script behavior and manipulate data.
What is shell used for?
A shell is used for command execution, process management, file handling, automation, and system administration in Unix/Linux environments.
Conclusion
In this article, we discussed the fundamentals of shell scripting, a powerful tool for automating tasks in Unix-based systems. We discussed the basics of writing shell scripts, including syntax, variables, loops, conditionals, and functions. Shell scripting enhances productivity by automating repetitive tasks and managing system operations efficiently. By mastering shell scripting, developers and system administrators can streamline workflows and improve system performance.