Bash Scripting Basics
# 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
readcommand.
-
Implement basic logical flow using
if/then/elsestatements.
-
Automate repetitive actions using
forloops.
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:
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.
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!)*
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 [ ].*
*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.
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
0to the operating system. If it fails, it returns a1(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 #!/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
``
chmod +x autobackup.sh
./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.
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?
-
2.
Identify the syntax error in the following Bash variable declaration: IP_ADDRESS = "192.168.1.5"
.
12. MCQs with Answers
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?
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 byrm -rf *. Explain the catastrophic risk of this script if the/var/logsdirectory 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/bindirectory and simply typingscript.
-
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.