
The Automation Engine: Writing Your First Bash Script
Turn your commands into code. Learn the foundational anatomy of a Linux shell script. Master the 'Shebang' line, understand file execution bits, and learn to pass arguments from the command line into your script.
Bash Scripting: From Command to Automation
Up until now, we have been using the Linux terminal "Live"—typing one command at a time. This is like playing a piano note by note. Bash Scripting is about writing the "Sheet Music." It allows you to save a sequence of commands into a file so you can run thousands of operations with a single keystroke.
In this lesson, we will move from a user of the shell to a Programmer of the shell.
1. Anatomy of a Shell Script ADAD
A shell script is simply a text file containing commands. However, it needs two special things to work properly as a script.
I. The Shebang (#!)
The very first line of every script must start with #!. This tells Linux which "Interpreter" should read this file.
#!/bin/bash: Use the standard Bash shell.#!/usr/bin/python3: Use Python to read this file.
II. The Execution Bit
Just because a file contains code doesn't mean Linux will "Run" it. You must give the file Execute permission.
chmod +x my_script.sh
2. Your First Script: hello.sh
Create a file named hello.sh and add the following:
#!/bin/bash
# This is a comment - it is ignored by the shell
echo "Starting my first automation..."
echo "My name is: $(whoami)"
echo "Today is: $(date)"
echo "My system has been up for: $(uptime -p)"
Running the script:
./hello.sh
Note: We use ./ to tell Bash to look in the "Current Directory" for the script.
3. Positional Parameters: Passing Info to Scripts
Scripts become useful when you can send them "Inputs." These are called Arguments.
$0: The name of the script itself.$1: The first argument.$2: The second argument.$#: The total number of arguments passed.
Example: greet.sh
#!/bin/bash
echo "Hello $1! You are currently in the $2 directory."
Running it: ./greet.sh Sudeep /var/log
4. The Exit Status: Success or Failure?
Every command in Linux returns a "hidden" number when it finishes.
- 0: Success.
- Non-zero (1-255): Failure.
You can see the status of the last command by checking the special variable $?.
ls /folder_that_doesnt_exist
echo $?
# Output: 2 (Generic error code)
5. Practical: The "Health Check" Script
Here is a script you might use as a sysadmin to quickly check if a server is ready for work.
#!/bin/bash
# server_check.sh
echo "--- PRE-FLIGHT CHECK ---"
# 1. Check if we are connected to the network
ping -c 1 8.8.8.8 > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "[OK] Internet is reachable."
else
echo "[FAIL] No internet connection!"
fi
# 2. Check Disk Space
FREE_DISK=$(df -h / | tail -1 | awk '{print $4}')
echo "[INFO] Disk space available: $FREE_DISK"
# 3. List top 3 memory users
echo "[INFO] Top processes:"
ps aux --sort=-%mem | head -4
6. Example: A Script Template Generator (Python)
If you find yourself creating scripts often, you don't want to manually type the shebang and run chmod every time. Here is a Python script that creates a new Bash script for you and sets the permissions.
import sys
import os
def create_shell_script(name):
"""
Bootstraps a new bash script with a shebang and sets execute bit.
"""
if not name.endswith(".sh"):
name += ".sh"
content = "#!/bin/bash\n\n# Created automatically by ShShell Architect\necho 'Script running...'\n"
with open(name, "w") as f:
f.write(content)
# Set permissions to 755 (rwxr-xr-x)
os.chmod(name, 0o755)
print(f"Successfully created executable script: {name}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python3 create_script.py [script_name]")
else:
create_shell_script(sys.argv[1])
7. Professional Tip: Path Environment
If you want to run your script from anywhere (just by typing my_script without the ./), move your script to the /usr/local/bin directory or add your home "bin" folder to your $PATH.
8. Summary
Scripts are the "Automated Memory" of a systems engineer.
#!bin/bashis the mandatory first line.chmod +xmakes the file "Alive."$1, $2, ...are the inputs from the user.$?tells you if the previous command worked.echois for output;#is for comments.
In the next lesson, we will learn how to make our scripts smarter by using Variables, Data Types, and User Input.
Quiz Questions
- What does the
#!(shebang) actually do when you run a script? - How do you find out the exit status of the command you just ran?
- Why do we usually run scripts with
./script.shinstead of justscript.sh?
Continue to Lesson 2: Variables and User Input—Dynamic Shell Scripting.