GUIDE

Bash-Scripting Part-1

πŸ“… June 12, 2026πŸ•’ 15 min read✍️ JSMSec

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

TopicsDescriptionPractice Ideas
Variables & Data TypesUsing strings, integers, arraysCreate a script that stores system info (hostname, IP, uptime) in variables and print them.
Conditional StatementsDecision making in scriptsCreate a script that checks if a service (e.g., ssh) is running and restarts if it's not.
Loops (for, while, etc)Repeating tasksCreate a loop that checks disk space every 5 seconds and logs it.
User Input (read)Take user input dynamicallyBuild a menu-driven tool that lets you choose which log file to view.
FunctionsOrganize and reuse codeWrap your log-checking code into a function and call it on demand.
Exit Status, Error HandlingHandle success/failure in scriptsBuild a backup script that shows success or failure based on tar command.
File HandlingRead/Write/append from filesCreate a log rotation script that archives logs older than 7 days.
Cron Jobs (Automation)Schedule tasksAutomate your backup script to run every night at 2 AM.
System CommandsCombining Linux commandsUse df, uptime, free, top, ps, etc., in meaningful scripts.
Networking ToolsScripted network checksPing 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:

  1. User-friendly interface
  2. Command execution
  3. File management
  4. Process management
  5. Automation
  6. Program capabilities

Types of Shells

Linux supports multiple shells.

ShellCommandDescription
Bourne ShellshOriginal UNIX shell
Bourne Again ShellbashMost popular shell
Korn ShellkshAdvanced shell
C ShellcshC-like syntax
TENEX C ShelltcshImproved C shell
Z ShellzshModern shell with many features
Fish ShellfishUser-friendly shell
ℹ️Note

The default shell on most Linux distributions is Bash (Bourne Again Shell).

Check your current shell:

terminal

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
common shebangs

#!/bin/sh #!/bin/bash #!/usr/bin/perl #!/usr/bin/tcl #!/bin/sed -f #!/bin/awk -f


Features of Bash

  1. Command history
  2. Auto-completion
  3. Variables
  4. Loops
  5. Conditions
  6. Functions
  7. Arithmetic
  8. Scripting
  9. 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:

bash

age=25 name=John salary=45000

ℹ️Note

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.

bash

echo $HOME echo $USER echo $PATH echo $PWD

Common Environment Variables

VariableMeaning
HOMEHome directory
USERCurrent username
PATHExecutable search path
PWDPresent working directory
HOSTNAMEComputer name
SHELLCurrent shell
LOGNAMELogin name
TERMTerminal type
ℹ️Note

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.

VariableMeaning
$0Name of the script
$1First command-line argument
$2Second 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
$HOMEHome directory (also an environment variable)
$PWDCurrent working directory (also an environment variable)
πŸ’‘Notice

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:

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:

terminal

./student.sh Rahul 22 Mumbai

Now, Bash assign values according to their position:

positional mapping

./student.sh Rahul 22 Delhi β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ └── $3 β”‚ β”‚ └────── $2 β”‚ └───────────── $1 └───────────────────────── $0

So internally:

values assigned

$0 = ./student.sh $1 = Rahul $2 = 22 $3 = Mumbai

ℹ️Note

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.

terminal

Variables β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ Built-in Variables User-defined Variables β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ Positional Shell Special Variables Parameters β”‚ β”‚ Environment Variables

Easy way to remember

Think of a company:

  1. User-defined variables are like notes you write yourself.
  2. Built-in variables are information your manager automatically gives you (today's task, employee ID, etc.)
  3. Environment variables are company-wide policies and settings that every employee and department can access.