Class 13 of 37 • Shell Scripting Fundamentals \t\t\t\t

How to Write and Run Shell Script in Linux

in this topic describe to how to write and run shell script in linux.following step are required to write shell script in linux.

1.Use any editor like vi,gedit to write shell script

2.in this topic used vi editor to write a shell script.Open terminal type $vi [script_name].sh then press insert key to transfer from command to insert mode.

3.Write your script

4.To store your script press ESC key and write :wq then enter

5.Now execute your scrip like this $sh [scrip_name].sh

Example



$vi script1.sh
#
#Hello Reader This is Shell Script Example Using Vi Editor
#
echo "Veewom"
#Press Esc
#:wq Save Script
#Execute Script
$sh script1.sh
Veewom
							

The 5-Stage Shell Script Lifecycle

To create robust scripts that adhere to enterprise production standards, understanding the complete lifecycle from code creation to kernel process execution is essential:

Linux Shell Script Lifecycle: Write, Shebang, Chmod Permissions, Execution and Exit Status Diagram

Figure 3: Detailed five-step execution flow of a Linux shell script.

Stage 1: The Shebang Line (#!/bin/bash)

The very first line of any professional Linux shell script must begin with a Shebang (a compound of Hash # and Bang !). When the Linux kernel executes a file via the execve() system call, it reads the initial two bytes (0x23 0x21). If detected, it invokes the binary interpreter specified right after the shebang:


#!/bin/bash         # Explicit path to GNU Bash
#!/bin/sh           # System default POSIX shell (dash/sh)
#!/usr/bin/env bash # Portable Shebang (searches PATH for bash)
							

Stage 2: File Permissions & chmod +x

When you save a text file in Linux, it receives default read/write permissions (typically -rw-r--r-- / 644). It cannot be executed directly unless you grant the execute bit (x):


# Check permissions before
$ ls -l myscript.sh
-rw-r--r-- 1 student student 152 Nov 2 10:00 myscript.sh

# Add execute permission for user, group, and others
$ chmod +x myscript.sh
# OR give full owner rights and read-execute to others (755)
$ chmod 755 myscript.sh

# Verify permissions
$ ls -l myscript.sh
-rwxr-xr-x 1 student student 152 Nov 2 10:01 myscript.sh
							

Stage 3: Methods of Running a Script

Execution Command How It Executes Does It Need chmod +x?
./myscript.sh Kernel reads Shebang and spawns a new subshell process. Yes (Execute permission is mandatory)
bash myscript.sh Directly passes script file as argument to the Bash interpreter. No (Only read permission needed)
source myscript.sh (or . myscript.sh) Executes commands directly in the current shell environment. No (Environment variables persist in current shell)

Practical Lab Scripts for BCA Students

Here are 2 practical exam-ready scripts frequently requested in BCA and CS university laboratory practicals:

Lab Program 1: System Information & Health Reporter


#!/bin/bash
# ==========================================================
# Script Name : sysinfo.sh
# Description : Displays current user, date, kernel, and disk space
# Author      : Veewom Linux Programming
# ==========================================================

clear
echo "=================================================="
echo "          SYSTEM INFORMATION REPORT               "
echo "=================================================="
echo "Logged in User  : $(whoami)"
echo "Current Date    : $(date '+%Y-%m-%d %H:%M:%S')"
echo "Hostname        : $(hostname)"
echo "Kernel Release  : $(uname -r)"
echo "System Uptime   : $(uptime -p)"
echo "--------------------------------------------------"
echo "Disk Space Usage:"
df -h / | awk 'NR==1 || NR==2'
echo "=================================================="
exit 0
							

Lab Program 2: Interactive Backup Script with Status Checking


#!/bin/bash
# ==========================================================
# Script Name : backup_docs.sh
# Description : Backs up directory into tar.gz with timestamp
# ==========================================================

SOURCE_DIR="$HOME/linux_practice"
BACKUP_DIR="$HOME/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="backup_${TIMESTAMP}.tar.gz"

# Create backup folder if it doesn't exist
mkdir -p "$BACKUP_DIR"

echo "Starting backup of $SOURCE_DIR ..."
tar -czf "$BACKUP_DIR/$BACKUP_FILE" -C "$SOURCE_DIR" .

# Check exit status of tar command ($?)
if [ $? -eq 0 ]; then
    echo "SUCCESS: Backup created at $BACKUP_DIR/$BACKUP_FILE"
    echo "File size: $(du -sh "$BACKUP_DIR/$BACKUP_FILE" | cut -f1)"
else
    echo "ERROR: Backup creation failed!" >&2
    exit 1
fi

exit 0
							

Debugging Shell Scripts

When a script does not produce expected results, use Bash's built-in debugging flags:

     bash -x script.sh : X-Trace mode prints every command and expanded arguments with a + prefix before execution.

     bash -n script.sh : No-exec mode checks the script for syntax errors without actually running any commands.

     set -euo pipefail : Include this at top of your script. It ensures the script immediately halts on error (-e), treats unset variables as an error (-u), and catches pipeline failures (-o pipefail).


Frequently Asked Questions (FAQ)

If the Shebang line is missing, the Linux kernel will default to executing the script using the system's fallback POSIX shell (usually /bin/sh). If your script uses Bash-specific extensions (like arrays, [[ ... ]], or string slicing), it may fail with syntax errors.

In Linux and Unix, every command or script returns an exit status between 0 and 255 upon termination. An exit code of 0 indicates complete success, while any non-zero value (1–255) represents an error or specific failure condition. You can check the exit code of the last command using echo $?.

Next Step in Your Linux Learning Path:

Understand reserved language keywords and built-in commands in Class 14: Shell Keywords.

Continue to Class 14: Shell Keywords → Previous: ← Overview of Script | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!