Skip to main content
Linux Command Line – Complete Beginner to Advanced Guide
CHAPTER 14 Beginner

Bash Scripting Basics

Updated: May 16, 2026
35 min read

# CHAPTER 14

Bash Scripting Basics

1. Introduction

Typing commands into the terminal is efficient, but what if you have to type the exact same sequence of 10 commands every Friday at 5:00 PM to backup a database? A network engineer does not type repetitively; they automate. Bash Scripting allows you to take any command you would normally type into the terminal, paste them all into a single text file, and execute them sequentially with one keystroke. A script transforms you from a user of the machine into a programmer of the machine. In this chapter, we will write our first shell script, declare the critical Shebang (#!), master variables, and introduce logical routing using if/else conditions and for loops.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the purpose of a shell script and the necessity of the Shebang (#!/bin/bash).
  • Grant execution permissions to a script file using chmod +x.
  • Declare and utilize variables within a Bash script.
  • Prompt a user for input using the read command.
  • Implement basic logical flow using if/then/else statements.
  • Automate repetitive actions using for loops.

3. Anatomy of a Bash Script

A Bash script is just a plain text file ending in .sh. There are two absolute requirements to make it work:

1. The Shebang (#!): The very first line of every script must tell the operating system *which* interpreter to use to read the code. For Bash, it is always:

bash
1
#!/bin/bash

2. Execution Permissions: By default, Linux text files are not allowed to run as programs (for security). You must manually grant the Execute (x) permission.

bash
12345678
# Create the file
touch backup.sh

# Make it executable!
chmod +x backup.sh

# Run the script (The ./ tells Linux to look in the current folder)
./backup.sh

4. Variables and User Input

Scripts are powerful because they are dynamic. You can store data in variables. *(Note: There are NO SPACES around the equals sign in Bash!)*
bash
123456789101112
#!/bin/bash

# Define a variable
SERVER_NAME="Database_01"

# Print the variable using a Dollar Sign ($)
echo "Starting backup for $SERVER_NAME"

# Ask the user a question
echo "What is your name?"
read USERNAME
echo "Welcome to the system, $USERNAME"

5. Conditional Logic (If / Else)

A script must be able to make decisions based on the state of the system. *Syntax Note: Bash requires spaces inside the square brackets [ ].*
bash
12345678910
#!/bin/bash

echo "Enter your age:"
read AGE

if [ $AGE -ge 18 ]; then
    echo "You are an adult. Access granted."
else
    echo "You are a minor. Access denied."
fi

*Common comparison operators:* -eq (equal), -ne (not equal), -gt (greater than), -lt (less than).

6. Automation (For Loops)

If you need to create 5 text files, you don't write 5 lines of code. You write a loop.
bash
12345678
#!/bin/bash

# Loop through a list of words
for FILE in report1 report2 report3
do
    echo "Creating file: $FILE.txt"
    touch $FILE.txt
done

7. Diagrams/Visual Suggestions

*Visual Concept: The Script Execution Pipeline* Draw a flowchart of the execution requirement: Box 1: nano script.sh (Writing code). Arrow points to Box 2: chmod +x script.sh (Unlocking the padlock). Arrow points to Box 3: ./script.sh (Rocket ship launching). This visual reinforces the mandatory middle step of execution permissions, which beginners invariably forget.

8. Best Practices

  • Use Exit Codes: When a Linux command succeeds, it silently returns a 0 to the operating system. If it fails, it returns a 1 (or higher). A professional script always checks if the previous command succeeded before continuing. You can check the success of the last command using the special variable $?.
bash
12345678910111213
  ping -c 1 google.com
  if [ $? -eq 0 ]; then
      echo "Internet is working!"
  fi
  ```

### 9. Common Mistakes
- **Spaces around the equals sign:** In Python or JavaScript, typing `name = "Alex"` is perfect. In Bash, typing `name = "Alex"` will cause a catastrophic crash. Bash interprets the first word (`name`) as a command to run, and fails. You MUST type `name="Alex"` with zero spaces.

### 10. Mini Project: Build a Backup Automation Script
Let's build a real-world DevOps tool!
1. `nano auto_backup.sh`
2. Write the following code:

bash #!/bin/bash

# Variables TARGETDIR="/var/log" BACKUPFILE="logbackup$(date +%F).tar.gz" DESTINATION="/tmp"

echo "Starting backup of $TARGETDIR..."

# Create the compressed tarball tar -czvf $DESTINATION/$BACKUPFILE $TARGETDIR 2>/dev/null

if [ $? -eq 0 ]; then echo "SUCCESS! Backup saved to $DESTINATION/$BACKUPFILE" else echo "ERROR! Backup failed." fi ``

  1. 3. Save and Exit.
  1. 4. Make it executable: chmod +x autobackup.sh
  1. 5. Run it: ./autobackup.sh
You just wrote a script that dynamically names a backup file based on today's date, compresses a system folder, and verifies its own success!

11. Practice Exercises

  1. 1. Explain the operational purpose of the Shebang (#!/bin/bash) at the top of a shell script. What happens if you run a script without one?
  1. 2. Identify the syntax error in the following Bash variable declaration: IP_ADDRESS = "192.168.1.5".

12. MCQs with Answers

Question 1

You write a perfect Bash script named deploy.sh and attempt to execute it by typing ./deploy.sh. The terminal instantly responds with "Permission denied." Which command must you run to resolve this?

Question 2

When writing an if statement in Bash, which specific comparison operator is used to check if an integer variable is "greater than or equal to" a specific number?

13. Interview Questions

  • Q: A junior engineer writes a script containing cd /var/logs followed by rm -rf *. Explain the catastrophic risk of this script if the /var/logs directory is accidentally deleted before the script runs, and how you would utilize an exit code check ($?) to secure it.
  • Q: Explain the mechanical difference between running a script by typing ./script.sh versus placing the script in the /usr/local/bin directory and simply typing script.
  • Q: Walk me through the fundamental syntax differences in assigning a variable in Bash versus evaluating a mathematical comparison inside a Bash if statement (specifically regarding spaces).

14. FAQs

Q: Why do I have to type
./ before the script name? Why can't I just type backup.sh? A: Remember the $PATH variable from Chapter 13? The shell only looks for commands inside specific system folders (like /bin). It does NOT look in your current folder for security reasons. Typing ./ explicitly forces the shell to look exactly "Right Here" in the current directory for the program.

15. Summary

In Chapter 14, we transitioned from manual administrators to automation engineers. We constructed proper Bash scripts by initiating them with the
#!/bin/bash Shebang and utilizing chmod +x to authorize execution. We stored dynamic strings within variables (strictly avoiding spaces), gathered input via read, and engineered complex decision-trees using if/else logic loops. Finally, we harnessed the for` loop to execute rapid, massive-scale repetitive tasks, culminating in a real-world automated backup tool that dynamically verified its own exit codes.

16. Next Chapter Recommendation

You can write scripts that modify the system, but who exactly is allowed to run those scripts? Proceed to Chapter 15: Linux Users and Groups.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·