Bash-Scripting Part-1
What is Bash-Scripting?
The primary command line interface to Unix/Linux is called the shell. One of the most popular shells, the Bourne shell, was created at Bell Labs by Stephen Bourne in 1979. A free updated version of the Bourne shell, called BASH (Bourne Again Shell), was developed by Brian Fox in 1987 and released in 1989. BASH is the default shell for most Linux distributions today.
Instead of constantly running and re-running BASH commands in the terminal, Linux system administrators often create files containing the sequence of BASH commands they wish to run. These files are called BASH scripts. Anything you can do from the command line can also be done using a BASH script.
Essential Topics in Shell Scripting
| Topics | Description | Practice Ideas |
|---|---|---|
| Variables & Data Types | Using strings, integers, arrays | Create a script that stores system info (hostname, IP, uptime) in variables and print them. |
| Conditional Statements | Decision making in scripts | Create a script that checks if a service (e.g., ssh) is running and restarts if it's not. |
| Loops (for, while, etc) | Repeating tasks | Create a loop that checks disk space every 5 seconds and logs it. |
| User Input (read) | Take user input dynamically | Build a menu-driven tool that lets you choose which log file to view. |
| Functions | Organize and reuse code | Wrap your log-checking code into a function and call it on demand. |
| Exit Status, Error Handling | Handle success/failure in scripts | Build a backup script that shows success or failure based on tar command. |
| File Handling | Read/Write/append from files | Create a log rotation script that archives logs older than 7 days. |
| Cron Jobs (Automation) | Schedule tasks | Automate your backup script to run every night at 2 AM. |
| System Commands | Combining Linux commands | Use df, uptime, free, top, ps, etc., in meaningful scripts. |
| Networking Tools | Scripted network checks | Ping all your VMs from one script and log response times. |
What is a Shell?
A shell is a command-line interpreter that acts as an interface between the user and the Linux kernel. It accepts commands from the user, interprets them, and asks the kernel to execute them.
Why do we need a Shell?
Without a shell, users would have to communicate directly with the kernel, which is nearly impossible.
The shell provides:
- User-friendly interface
- Command execution
- File management
- Process management
- Automation
- Program capabilities
Types of Shells
Linux supports multiple shells.
| Shell | Command | Description |
|---|---|---|
| Bourne Shell | sh | Original UNIX shell |
| Bourne Again Shell | bash | Most popular shell |
| Korn Shell | ksh | Advanced shell |
| C Shell | csh | C-like syntax |
| TENEX C Shell | tcsh | Improved C shell |
| Z Shell | zsh | Modern shell with many features |
| Fish Shell | fish | User-friendly shell |
The default shell on most Linux distributions is Bash (Bourne Again Shell).
Check your current shell:
echo $SHELL
The Shebang (#!)
The sha-bang (#!) at the head of a script tells your system that this file is a set of commands to be fed to the command interpreter indicated.
The #! is actually a two-byte magic number β a special marker that designates a file type, or in this case an executable shell script.
- The sha-bang is a path name
- This is a path to the program that interprets the commands in the script, whether it be a shell, a programming language, or a utility
- This command interpreter then executes the commands in the script, starting at the top
#!/bin/sh #!/bin/bash #!/usr/bin/perl #!/usr/bin/tcl #!/bin/sed -f #!/bin/awk -f
Features of Bash
- Command history
- Auto-completion
- Variables
- Loops
- Conditions
- Functions
- Arithmetic
- Scripting
- Job control
Variables
As with other programming languages, variable definition is similar across most languages. But in Bash there are some important differences in how variables work.
The biggest difference between Bash and programming languages like C, C++, Java, or Python is that Bash treats almost everything as text (strings). Variables don't have a declared data type.
For example:
age=25 name=John salary=45000
In the above code, although 25 and 45000 look like numbers, Bash stores them as strings (text).
Environment Variables
Environment variables store system information. These variables are available to the current shell and any programs or child processes started from it.
echo $HOME echo $USER echo $PATH echo $PWD
Common Environment Variables
| Variable | Meaning |
|---|---|
| HOME | Home directory |
| USER | Current username |
| PATH | Executable search path |
| PWD | Present working directory |
| HOSTNAME | Computer name |
| SHELL | Current shell |
| LOGNAME | Login name |
| TERM | Terminal type |
These variables provide information about your environment and help programs know where to find files, commands, and configuration.
Built-in Variables
Built-in variables are special variables that Bash creates automatically. You do not create them yourself β Bash maintains their values while your shell or script is running.
| Variable | Meaning |
|---|---|
| $0 | Name of the script |
| $1 | First command-line argument |
| $2 | Second command-line argument |
| $# | Number of command-line arguments |
| $@ | All command-line arguments |
| $? | Exit status of the last command |
| $$ | Process ID (PID) of the current shell |
| $HOME | Home directory (also an environment variable) |
| $PWD | Current working directory (also an environment variable) |
Some built-in variables are also environment variables β we will come back to that.
Positional Parameters
$1, $2, $3 are called positional parameters because their meaning depends on their position in the command line.
For example, suppose you have created the below script in a file student.sh:
#!/bin/bash
echo "Script Name : $0" echo "First Argument : $1" echo "Second Argument : $2" echo "Third Argument : $3"
Run it like this from the terminal:
./student.sh Rahul 22 Mumbai
Now, Bash assign values according to their position:
./student.sh Rahul 22 Delhi β β β β β β β βββ $3 β β βββββββ $2 β ββββββββββββββ $1 ββββββββββββββββββββββββββ $0
So internally:
$0 = ./student.sh $1 = Rahul $2 = 22 $3 = Mumbai
The first argument always becomes $1, the second becomes $2, and so on. This is how positional parameters are defined.
Are Built-in Variables and Environment Variables the Same?
In simple words β No. They overlap in some cases, but they are different categories.
Variables β ββββββββββββββββ΄βββββββββββββββ β β Built-in Variables User-defined Variables β βββββββββββββββββ β β Positional Shell Special Variables Parameters β β Environment Variables
Easy way to remember
Think of a company:
- User-defined variables are like notes you write yourself.
- Built-in variables are information your manager automatically gives you (today's task, employee ID, etc.)
- Environment variables are company-wide policies and settings that every employee and department can access.