Linux Mastery

The Human Knowledge Project


Chapter 20 — Shell Scripting Fundamentals


Why This Chapter Matters

One of Linux's greatest strengths is automation.

Rather than performing repetitive tasks manually, Linux users can write scripts that perform those tasks automatically.

Shell scripts are used to automate:

The Linux shell is more than a command interpreter—it is also a programming environment.

Learning shell scripting is a major step toward Linux mastery.


Learning Objectives

Upon completing this chapter, you will be able to:


Introduction

Throughout this course you have learned dozens of Linux commands.

Individually, these commands are useful.

Together, they become extraordinarily powerful.

Shell scripting allows you to combine multiple Linux commands into reusable programs that perform work automatically.

Instead of typing the same commands repeatedly, you write them once and allow Linux to execute them whenever needed.


1. What Is a Shell Script?

A shell script is a plain text file containing Linux commands.

When executed, the shell reads the file and performs each command in order.

Rather than entering commands manually one at a time, a script performs the entire sequence automatically.

Shell scripts can range from a few lines to thousands of lines depending on the task being automated.


2. Why Shell Scripts Matter

Shell scripts help users:

Many system administrators perform much of their daily work through shell scripts.

THKI Insight

Good administrators automate repetitive work.

If you find yourself typing the same commands repeatedly, it is often a sign that a shell script could save time and reduce mistakes.


3. Script Files

Shell scripts are ordinary text files.

Many use the extension:


.sh

Example:


backup.sh

The extension is helpful because it tells people that the file contains a shell script.

However, Linux does not require script files to use any particular extension.

A script named:


backup

works just as well.


4. The Shebang

Most shell scripts begin with a special first line called the shebang.

Example:


#!/bin/bash

The shebang tells Linux which interpreter should execute the script.

THKI Memory Aid


#!/bin/bash
        ↓
Use Bash
to run this script

Without the shebang, Linux may not know which interpreter should process the file.


5. Creating Your First Script

Create a new script using a text editor.

Example:


nano hello.sh

Enter the following contents:


#!/bin/bash
echo "Hello Linux"

Save the file and exit the editor.

Although this is a simple example, it demonstrates the basic structure of every Bash script.


6. Making a Script Executable

Before Linux will execute a script directly, it must have execute permission.

Grant execute permission with:


chmod +x hello.sh

The +x option adds execute permission to the file.

Without execute permission, Linux treats the file as ordinary text rather than a program.


7. Running a Script

Execute the script using:


./hello.sh

Output:


Hello Linux

The script runs exactly as though you had typed the echo command yourself.


8. Why ./ Is Required

Notice that the script was started using:


./hello.sh

rather than simply:


hello.sh

The current directory is usually not included in the PATH environment variable.

The prefix:


./

tells Linux:

Run the program located in the current directory.

Without it, Linux searches only the directories listed in PATH.


9. Comments

Comments explain how a script works.

They are ignored during execution.

Example:


# This is a comment
echo "Hello Linux"

Comments help:

Well-documented scripts are much easier to understand and maintain months—or even years—later.

THKI Memory Aid


You
   ↓
Write Script
   ↓
Linux Executes
   ↓
Work Happens Automatically

Automation is one of the defining strengths of Linux.



10. Variables

Variables allow scripts to store information for later use.

Creating a variable:


NAME="Norm"

Display the variable:


echo $NAME

Output:


Norm

Variables make scripts flexible because values can be changed without rewriting the program.

THKI Memory Aid


NAME="Norm"
↓
Variable
stores
information

11. Variable Syntax

Variable names should be descriptive.

Examples:


USERNAME="alice"
COUNT=10
BACKUP_DIR="/home/norm/Backups"

One important rule:

Do not place spaces around the equals sign.

Correct:


NAME="Linux"

Incorrect:


NAME = "Linux"

The shell interprets these very differently.


12. Reading User Input

Scripts can request information from the user.

Example:


read NAME

A more user-friendly version:


echo "Enter your name:"
read NAME

Display the response:


echo "Hello $NAME"

The value entered by the user is stored in the variable:


NAME

13. Environment Variables

Shell scripts can use environment variables that already exist in Linux.

Examples:


echo $HOME
echo $USER
echo $PATH
echo $SHELL

These variables allow scripts to adapt automatically to the current user and system.


14. Command Substitution

Sometimes a script needs the output from another command.

Command substitution stores that output inside a variable.

Example:


DATE=$(date)

Display it:


echo $DATE

Possible output:


Tue May 13 09:42:16 PDT 2026

Any command whose output is useful may be captured this way.


15. Making Decisions with if

Scripts often need to make decisions.

Example:


if [ -f notes.txt ]
then
    echo "File exists."
fi

This script checks whether:


notes.txt

exists.

If it does, the message is displayed.


16. Understanding the if Statement

The previous example contains several parts.

| Element | Purpose |

|---------|---------|

| if | Begin a condition |

| [ ] | Evaluate a test |

| -f | Test whether a file exists |

| then | Execute commands if true |

| fi | End the if statement |

Every if block must end with:


fi

which is simply:


if

spelled backwards.


17. Comparison Operators

Shell scripts support several comparison operators.

Numeric Comparisons

| Operator | Meaning |

|-----------|---------|

| -eq | equal |

| -ne | not equal |

| -gt | greater than |

| -lt | less than |

| -ge | greater than or equal |

| -le | less than or equal |

Example:


COUNT=10
if [ $COUNT -gt 5 ]
then
    echo "Greater than five."
fi

18. String Comparisons

Strings may also be compared.

Example:


NAME="Norm"
if [ "$NAME" = "Norm" ]
then
    echo "Welcome!"
fi

Notice that string variables are enclosed in quotation marks.

Quoting variables helps prevent unexpected behavior when values contain spaces.


19. File Tests

Shell scripts can test many file properties.

| Test | Meaning |

|------|---------|

| -f | Regular file exists |

| -d | Directory exists |

| -r | Readable |

| -w | Writable |

| -x | Executable |

Example:


if [ -d Documents ]
then
    echo "Directory found."
fi

20. Using if / else

Sometimes two different actions are required.

Example:


if [ -f notes.txt ]
then
    echo "File found."
else
    echo "File not found."
fi

The else section executes only when the condition is false.


21. for Loops

A for loop repeats commands for each item in a list.

Example:


for FILE in *.txt
do
    echo "$FILE"
done

This loop displays the name of every text file in the current directory.

for loops are widely used for processing groups of files.


22. while Loops

A while loop repeats as long as a condition remains true.

Example:


COUNT=1
while [ $COUNT -le 5 ]
do
    echo "$COUNT"
    COUNT=$((COUNT + 1))
done

Output:


1
2
3
4
5

23. Arithmetic Expansion

Shell scripts perform arithmetic using:


$(( ))

Example:


COUNT=$((COUNT + 1))

This increases the value stored in:


COUNT

Arithmetic expansion allows scripts to count, calculate, and track values.


24. Functions

Functions group related commands into reusable blocks.

Example:


hello() {
    echo "Hello Linux"
}

Run the function:


hello

Functions improve:

Large shell scripts often contain many functions.


25. Command-Line Arguments

Scripts can receive information from the command line.

Example script:


#!/bin/bash
echo "First argument: $1"

Run it:


./script.sh hello

Output:


First argument: hello

Useful special variables include:

| Variable | Meaning |

|----------|---------|

| $0 | Script name |

| $1 | First argument |

| $2 | Second argument |

| $# | Number of arguments |

Arguments make scripts much more flexible because the same script can perform different tasks depending on the values supplied by the user.



26. Exit Status

Nearly every Linux command returns an exit status after it finishes.

An exit status tells the shell whether the command succeeded.

Common values include:

| Exit Code | Meaning |

|-----------|---------|

| 0 | Success |

| Non-zero | Error or failure |

To display the exit status of the previous command:


echo $?

Shell scripts frequently test exit codes to determine what action to perform next.


27. Automation

The true strength of shell scripting is automation.

Rather than performing repetitive work manually, Linux users create scripts that execute tasks automatically.

Common examples include:

Automation saves time while reducing the likelihood of human error.

THKI Insight

Computers excel at repetitive work.

People excel at solving new problems.

Let the computer perform repetitive tasks so you can focus on higher-level thinking.


28. Example Backup Script

A simple backup script might contain:


#!/bin/bash
tar -czvf backup.tar.gz Documents/

Running the script creates a compressed archive of the Documents directory.

Although simple, this demonstrates how several Linux commands can be combined into a reusable tool.


29. Example Update Script

Many Linux users create update scripts similar to:


#!/bin/bash
sudo apt update
sudo apt upgrade
sudo apt autoremove

Executing the script performs several maintenance tasks automatically.

Scripts like this are commonly used on personal workstations.


30. Scheduling Scripts

Many Linux systems schedule scripts automatically.

One of the oldest scheduling systems is:


cron

A scheduled task is often called a:


cron job

Examples include:

Scheduling allows Linux to perform work even when no one is using the computer.


31. Debugging Scripts

Even experienced programmers make mistakes.

Common script problems include:

One of the easiest ways to test a script is:


bash script.sh

This executes the script directly through Bash.


32. Tracing Script Execution

To watch a script execute one command at a time:


bash -x script.sh

The -x option displays each command as Bash executes it.

This is one of the most useful debugging techniques available.


33. Script Permissions

Shell scripts are programs.

Like other programs, they require execute permission before Linux will launch them directly.

Grant execute permission with:


chmod +x script.sh

Without execute permission, Linux treats the file as ordinary text.


34. Real-World Administrative Workflow

A Linux administrator may write scripts to:

Many administrative tasks that would require dozens of commands manually can be completed by running a single script.


35. Safety Note

Shell scripts are powerful.

They can:

Always read a script before running it—especially if it came from an unknown source.

Be particularly cautious when scripts contain:


sudo

or are intended to run as:


root

Understanding what a script does before executing it is an essential security habit.


Chapter Summary

| Concept | Purpose |

|---------|---------|

| Shell script | Automate Linux commands |

| Shebang | Specify the interpreter |

| Variables | Store information |

| read | Accept user input |

| Command substitution | Capture command output |

| if / else | Decision making |

| Loops | Repeat operations |

| Functions | Reusable code |

| Arguments | Pass information to scripts |

| cron | Schedule automated tasks |

| bash -x | Debug scripts |


Key Ideas

Shell scripting transforms Linux from a collection of individual commands into a powerful automation platform.

Understanding:

allows you to automate complex tasks with surprisingly little code.

More importantly, shell scripting demonstrates one of Linux's defining philosophies:

Build powerful systems by combining many small, well-designed tools.


Practice Exercises

  1. Create a script that displays Hello Linux.
  2. Make the script executable.
  3. Run the script.
  4. Add comments explaining what the script does.
  5. Create variables and display their values.
  6. Prompt the user for input using read.
  7. Display environment variables inside a script.
  8. Store the output of date in a variable.
  9. Write an if statement that checks whether a file exists.
  10. Add an else clause.
  11. Compare numeric values.
  12. Compare string values.
  13. Test whether a directory exists.
  14. Create a for loop that displays every .txt file.
  15. Create a while loop that counts from 1 to 10.
  16. Use arithmetic expansion with $(( )).
  17. Create and call a function.
  18. Accept command-line arguments.
  19. Display $0, $1, $2, and $#.
  20. Display the previous command's exit status.
  21. Create a simple backup script.
  22. Create an update script.
  23. Run a script with:
  24. 
    bash script.sh
    
  25. Debug a script using:
  26. 
    bash -x script.sh
    
  27. Create a script that:
  1. Combine variables, loops, and conditions into a single script.
  2. Explain why automation is valuable.
  3. Describe a real-world task that could be automated with a shell script.
  4. Explain how shell scripting reflects the Linux philosophy of small tools working together.
  5. Experiment safely, improve your scripts, and document your observations.

Congratulations

You have completed Linux Mastery Version 1.0.

Throughout this course you have learned how to:

These skills form a solid foundation for working with Linux as a desktop user, power user, developer, or system administrator.

Learning Linux is a journey rather than a destination.

The most effective way to continue improving is to use Linux regularly, experiment safely, and build increasingly ambitious projects.

The appendices that follow provide deeper reference material on important topics introduced throughout this course.

Future editions of Linux Mastery and additional THKI courses will expand on these concepts with more advanced techniques, real-world projects, and practical applications.

Thank you for learning with The Human Knowledge Institute.

We wish you success in your continued exploration of Linux and the broader world of computing.