Shell Script Examples (original) (raw)

Last Updated : 6 Jun, 2026

Shell scripting in Linux allows users to automate tasks by writing a sequence of commands in a script file. It helps reduce manual effort, improve efficiency and ensure consistency in repetitive operations. Scripts can handle file management, system monitoring and process automation with minimal user interaction. This makes shell scripting an essential skill for system administrators, developers and anyone working with Linux environments.

Basic Concepts of Shell Scripting

Shell scripts are plain text files containing a series of commands executed by a shell interpreter such as Bash. Each script follows a structured format, starting with the interpreter declaration and followed by executable commands. Understanding these foundational elements is important before moving to practical examples.

1. Shebang (#!) in Shell Script

The shebang (#!) defines the interpreter that will execute the script. Without it, the system may not know which shell to use, leading to unexpected behavior.

**Example:

#!/bin/bash
echo "Hello World"

**Output:

shebang-scr

Script of shebang example

shebang-scr-outp

Output of script

2. Running a Shell Script

A script must have executable permissions before it can be run directly. Without execute permission, the script will fail with a permission error

**Example:

chmod +x myscript.sh
./myscript.sh

**Note: Replace "myscript.sh" with your script name.

3. Printing Output Using echo

The echo command is used to display text or variable values on the terminal.

vim myscript.sh

**Script:

#!/bin/bash

This script prints "GeeksforGeeks" to the terminal

echo "GeeksforGeeks"

**Output:

myscript

myscript.sh

4. Explain the purpose of the echo command in shell scripting.

The echo command is used to display text or variables on the terminal. It is commonly used for printing messages, variable values and generating program output.

**Output:

echogfg

echo GFG

5. Variables in Shell Scripting

Variables are used to store data such as strings, numbers or command outputs. They allow reuse of values throughout the script without repeating them. In shell scripting, variables do not require explicit data type declaration.

**Example:

#!/bin/bash

Assigning a value to a variable

name="Sam"
age=24

echo $name
echo $age

**Output:

ex5

Variables in script

6. Taking User Input Using read

The read command is used to accept input from the user during script execution. The entered value is stored in a variable and can be used later in the script.

**Example: Shell script that takes a user name as input and greets the user.

#!/bin/bash

Prompt the user to enter their name

echo "Enter your name:"

Read user input and store it in the variable 'name'

read name

Display a greeting message using the stored input

echo "Hello, $name! Nice to meet you."

**Output:

ex6

User Input Using read command

Comments are used to add explanations inside a script. They are ignored by the interpreter and do not affect execution. They improve readability and help in understanding the script logic.

**Example:

#!/bin/bash

This is a comment explaining the purpose of the script

echo "gfg"

**Output:

ex7_1

Script of comment

ex7

Ignoring comment in script

8. Conditional Statements (if-else)

Conditional statements in Bash are used to execute different blocks of code depending on whether a given condition evaluates to true or false. They are essential for controlling the flow of a script and making decisions based on input or variable values.

**Example 1. Shell script that checks whether a number is greater than 5

#!/bin/bash

Assign a value to the variable 'num'

num=10

Check if the value of num is greater than 5

if [ $num -gt 5 ]; then
echo "Number is greater than 5"
else
echo "Number is 5 or less"
fi

**Output:

ex8_1

Checks whether a number is greater than 5

**Example 2. Shell script that checks if a file exists in the current directory.

This script checks whether a file named example.txt exists in the current directory and prints a message accordingly.

#!/bin/bash

Define the file name to check

file="example.txt"

Check if the file exists

if [ -e "$file" ]; then
echo "File exists: $file"
else
echo "File not found: $file"
fi

**Output:

ex8_2

Checks if a file exists in the current directory

9. Single Quotes vs Double Quotes

Quotes are used to define string values in shell scripting, but they behave differently based on how Bash interprets them. Understanding this difference is important for correct output in scripts.

**Script:

#!/bin/bash

var="Linux"

Single quotes: literal output

echo '$var'

Double quotes: variable gets expanded

echo "$var"

**Output:

ex9

Single Quotes vs Double Quotes

10. Command-Line Arguments in Shell Script

Command-line arguments allow users to pass values to a shell script at runtime. These values are accessed using positional parameters such as 0,0, 0,1, $2, etc., which represent the script name and the arguments provided.

**Example:

#!/bin/bash

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"

**Run:

./script.sh Hello World

**Output:

10ex_arg

Command-Line Arguments

11. for Loop in Shell Scripting

The for loop is used to iterate over a list of values or array elements. It executes a block of commands repeatedly for each item in the list.

**Example: Loop through a list of fruits

#!/bin/bash

Define an array of fruits

fruits=("apple" "banana" "cherry")

Loop through each element in the array

for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done

**Output:

11_Loop

for Loop

12. Shell Script to Calculate Sum from 1 to N Using a Loop

This script calculates the sum of all integers from 1 to a user-provided number N using a for loop.

**Example: Sum of First N Numbers

#!/bin/bash

Ask user for input

echo "Enter a number (N):"
read N

Initialize sum variable

sum=0

Loop from 1 to N

for (( i=1; i<=N; i++ )); do
sum=$((sum + i))
done

Display final result

echo "Sum of integers from 1 to Nis:N is: Nis:sum"

**Output:

12_cal_sum_n

Calculating sum from 1 to N using a loop

13. while Loop in Shell Scripting

A while loop is used in shell scripting to repeatedly execute a set of commands as long as a specified condition is true. The loop continues executing the commands until the condition becomes false.

**Syntax of while loop:

while [ condition ]; do
# commands to execute
done

**Example: Print Numbers from 1 to 5

#!/bin/bash

counter=1

while [ $counter -le 5 ]; do
echo "Number: $counter"
counter=$((counter + 1))
done

**Output:

13_whl_loop

while loop

14. Standard Output vs Standard Error

Shell scripting uses different output streams to separate normal output and error messages. This helps in debugging and redirecting outputs efficiently.

**Example:

#!/bin/bash

echo "This is normal output"
ls invalid_file

**Output:

14_std_ot_er

Standard Output vs Standard Error

15. Conditional Statements in Shell Scripting

Conditional statements allow a shell script to make decisions and control the flow of execution based on whether certain conditions are true or false. They help run different commands depending on the situation.

**Basic Structure:

if [ condition ]; then
# commands if condition is true
elif [ another_condition ]; then
# commands if another condition is true (optional)
else
# commands if all conditions are false (optional)
fi

16. Reading Lines from a File in Shell Scripting

In shell scripting, we can read a file line by line using a while loop with the read command. This is a safe and efficient way to process file content without loading the entire file into memory.

**Example: Read a File Line by Line

#!/bin/bash

file="/home/gfg0913/shl_ex/example.txt"

Check if file exists

if [ -e "$file" ]; then

# Read file line by line  
while IFS= read -r line; do  
    echo "Line read: $line"  
done < "$file"

else
echo "File not found: $file"
fi

**Output:

16_reading_line

Reading Lines from a File

17. Shell Script to Count Occurrences of a Word in a File

This script asks the user for a word and a file name, then counts how many times the word appears in the file.

**Example: Search and Count a Word

#!/bin/bash

Take user input

echo "Enter the word to search for:"
read target_word

echo "Enter the filename:"
read filename

Count occurrences of the word

count=$(grep -o -w "$target_word" "$filename" | wc -l)

Display result

echo "The word '$target_word' appears counttimesin′count times in 'counttimesinfilename'."

**Output:

17_occrn_cnt

Count Occurrences of a Word in File

18. Shell Script Function to Calculate Factorial

A function in shell scripting helps organize reusable code. This script defines a function to calculate the factorial of a number.

#!/bin/bash

Function to calculate factorial

calculate_factorial() {
num=$1
fact=1

for ((i=1; i<=num; i++)); do  
    fact=$((fact * i))  
done

echo $fact  

}

Take input from user

echo "Enter a number:"
read input_num

Call function and store result

factorial_result=$(calculate_factorial $input_num)

Display result

echo "Factorial of inputnumis:input_num is: inputnumis:factorial_result"

**Output:

18_Clclt_Fctrl

Calculation of Factorial

19. Handling Ctrl+C (SIGINT) in Shell Scripting

In shell scripting, Ctrl+C (SIGINT) is an interrupt signal sent by the user to stop a running program. We can handle this signal using the trap command to safely stop the script or perform cleanup tasks before exiting.

**Example: Handling Ctrl+C in a Script

This script catches the Ctrl+C interrupt and runs a cleanup function instead of stopping abruptly.

#!/bin/bash

Function to run when script is interrupted

cleanup() {
echo "Script interrupted (Ctrl+C pressed). Cleaning up before exit..."
exit 1
}

Trap Ctrl+C (SIGINT) signal

trap cleanup SIGINT

echo "Script is running..."
sleep 10
echo "Script completed successfully."

**Output:

19_Hdlng_Ctrl

Handling Ctrl+C (SIGINT)

20. Removing Duplicate Lines from a File

Duplicate lines in a file can be removed to clean data and improve readability. This is commonly used in log processing and data preprocessing.

**Example: Here is our linux script in which we will remove duplicate lines from a text file.

#!/bin/bash

Input and output file names

input_file="input.txt"
output_file="output.txt"

Check if input file exists

if [ -e "$input_file" ]; then

# Sort and remove duplicate lines  
sort "$input_file" | uniq > "$output_file"

echo "Duplicate lines removed successfully."  
echo "Output saved in $output_file"

else
echo "File not found: $input_file"
fi

**Output:

20_Rmvng_Dplct_Ln

duplicate line removing

21. Generating a Secure Random Password

Random password generation is used in security-related scripts to create strong credentials automatically. It helps improve system security by avoiding predictable passwords.

**Example: Password Generator Script

#!/bin/bash

Function to generate a random password

generate_password() {
tr -dc 'A-Za-z0-9!@#$%^&*()_+{}[]' < /dev/urandom | fold -w 12 | head -n 1
}

Generate and store password

password=$(generate_password)

Display result

echo "Generated password: $password"

**Output:

21_Gnrtng_Scr_Rndm_Pswd

Generating a Secure Random Password

22. Calculating Total Size of a Directory

Directory size calculation is used to monitor disk usage and manage storage efficiently. It helps identify how much space files inside a directory are consuming.

**Example: Total Size of a Directory

#!/bin/bash

Directory path

directory="/path/to/your/directory"

Calculate total size

total_size=$(du -ch "$directory" | grep total | awk '{print $1}')

Display result

echo "Total size of files in directory:directory: directory:total_size"

**Output:

22_clc_ttl_sz_drc

Calculating Total Size of a Directory

23. Difference Between if and elif

if and elif are used in conditional statements to control decision-making in scripts. They allow execution of different blocks based on multiple conditions.

if Statement elif Statement
Used to check the initial condition in a shell script decision structure Provides alternative conditions when the initial if condition is false
Used to start a conditional block Used after if to test additional conditions
Only one if block is allowed Multiple elif blocks can be used; only one else block (optional)
Executes its block if the condition is true; otherwise control moves to elif/else if present Evaluated only if previous conditions are false; if true, its block runs and the rest of the chain is skipped
Can be nested inside other if, elif or else blocks Cannot start a nested chain on its own, but can be used inside if or else blocks

Let’s understand it with an example.

#!/bin/bash

number=5

Simple if-else example

if [ $number -gt 10 ]; then
echo "$number is greater than 10"
else
echo "$number is not greater than 10"
fi

echo "--------"

if-elif-else example

if [ $number -gt 10 ]; then
echo "$number is greater than 10"

elif [ $number -eq 10 ]; then
echo "$number is equal to 10"

else
echo "$number is less than 10"
fi

**Output:

23_if_elif

if_elif difference

24. Finding and Listing Empty Files in a Directory

Empty file detection is useful for cleaning up unused files and managing storage efficiently. The find command is commonly used for this purpose.

#!/bin/bash

Take directory path from command-line argument

directory="$1"

Check if directory is provided

if [ -z "$directory" ]; then
echo "Usage: $0 "
exit 1
fi

Check if valid directory

if [ ! -d "$directory" ]; then
echo "Error: '$directory' is not a valid directory."
exit 1
fi

Find and list empty files

echo "Empty files in $directory:"
find "$directory" -type f -empty

**Output:

24_fnd_empt_fl

Finding and Listing Empty Files in a Directory

**Note: We need to provide a directory as an argument when running the script. Here we have used the path of current directory "/home/gfg0913"

25. Purpose of the read Command

The read command is used to take input from the user during script execution. It pauses the script, waits for the user to type a value and stores that value in a variable. This makes scripts interactive and dynamic.

**Syntax:

read variable_name

**Example: Asks the user for their name and displays a greeting message.

#!/bin/bash

echo "Please enter your name:"
read name

echo "Hello, $name!"

**Output:

25_read_cmd_prps

read Command

26. Converting Filenames to Lowercase in a Directory

File renaming operations are useful for maintaining consistency in naming conventions. Converting filenames to lowercase helps standardize file systems and avoid case-related issues.

#!/bin/bash

Take directory path from command-line argument

dir="$1"

Check if directory is provided

if [ -z "$dir" ]; then
echo "Usage: $0 "
exit 1
fi

Check if valid directory

if [ ! -d "$dir" ]; then
echo "Error: '$dir' is not a valid directory."
exit 1
fi

Move into directory

cd "$dir" || exit

Loop through all files

for file in *; do
if [ -f "$file" ]; then

    # Convert filename to lowercase  
    newname=$(echo "$file" | tr 'A-Z' 'a-z')

    # Rename file  
    mv "$file" "$newname"  
fi  

done

echo "Filenames converted to lowercase successfully."

**Output:

26_cnvrt_flnm_lwrcs

Converting Filenames to Lowercase

**Note: You must provide a directory as an argument when running the script. In this example, the current directory is used by passing . (a single dot), which represents the current working directory.

27. Arithmetic Operations in Shell Scripting

Arithmetic operations in shell scripting are used to perform mathematical calculations like addition, subtraction, multiplication and division. The most common methods are Arithmetic Expansion, expr and let.

**Example: Different Ways to Perform Addition

#!/bin/bash

num1=10
num2=5

Method 1: Arithmetic Expansion (Recommended)

result=$((num1 + num2))
echo "Sum (Arithmetic Expansion): $result"

Method 2: Using expr command

sum=$(expr num1+num1 + num1+num2)
echo "Sum (expr): $sum"

Method 3: Using let command

let "sum = num1 + num2"
echo "Sum (let): $sum"

**Output:

27_arth_opr

Arithmetic Operations

28. Checking Network Host Reachability

Host reachability checks are used to verify whether a system or server is accessible over a network. The ping command is commonly used for this purpose.

**Example: Check If a Host is Reachable

#!/bin/bash

Take host from command-line argument

host="$1"

Check if host is provided

if [ -z "$host" ]; then
echo "Usage: $0 "
exit 1
fi

Send 4 ICMP packets

ping -c 4 "$host"

Check result of ping command

if [ $? -eq 0 ]; then
echo "Host is reachable"
else
echo "Host is not reachable"
fi

**Output:

28_chk_ntwrk_hst

Checking Network Host Reachability

**Note: A hostname must be provided as an argument when running the script. In this example, the hostname used is: www.geeksforgeeks.org

29. Finding the Greatest Element in an Array

Arrays in shell scripting are used to store multiple values in a single variable. Finding the maximum value is useful in data processing and comparisons.

**Example: Find Maximum Value in an Array

#!/bin/bash

Define an array of numbers

array=(3 56 24 89 67)

Assume first element is the maximum

max=${array[0]}

Loop through all elements

for num in "${array[@]}"; do
if [ num−gtnum -gt numgtmax ]; then
max=$num
fi
done

Display the result

echo "Greatest element: $max"

**Output:

29_fnd_grt_ele_arr

Finding the Greatest Element in an Array

30. Calculating Sum of Array Elements

Array processing is commonly used in shell scripting for performing aggregate operations. Summing all elements in an array helps in basic data calculations and analysis.

**Example: Find Sum of Array Elements

#!/bin/bash

Define an array of numbers

array=(1 65 22 19 94)

Initialize sum to 0

sum=0

Loop through each element of the array

for num in "${array[@]}"; do
sum=$((sum + num))
done

Display final result

echo "Sum of elements: $sum"

**Output:

30_cal_sum_arr

Calculating Sum of Array Elements