NANDHOO.

Chapter 5: Scripting 101

A shell script is an executable file containing a sequence of commands that the shell parses and executes. By combining simple commands with variables and logic, you can create complex automation workflows that save hours of manual labor.

I. Anatomy of a Script

A professional shell script follows a specific structure to ensure portability, readability, and correct execution.

1. The Shebang (#!)

The first line of your script tells the kernel which interpreter to use. While #!/bin/bash is common, using /usr/bin/env is the professional standard for portability across different Unix systems.

#!/usr/bin/env bashMAGIC NUMBERINTERPRETER PATH

2. The Header Comments

Always include metadata at the top of your script to help others (and your future self) understand its purpose.

#!/usr/bin/env bash
#
# Script: backup_db.sh
# Description: Dumps the PostgreSQL database and uploads to S3.
# Author: Jane Doe (jane@example.com)
# Date: 2024-05-20
#

II. Variable Best Practices

In shell scripting, variables are untyped (usually treated as strings).

1. No Spaces Rule

You must not have spaces around the equals sign.

  • NAME="Jane"
  • NAME = "Jane" ❌ (This tells the shell to run a command named NAME with = as an argument).

2. Quoting is Mandatory

To prevent "word splitting" and "glob expansion," always wrap your variables in double quotes when accessing them.

FILE_NAME="My Document.txt"
# WRONG: rm $FILE_NAME  -> Shell tries to delete 'My' and 'Document.txt'
# RIGHT: rm "$FILE_NAME" -> Shell deletes 'My Document.txt'

III. Special Shell Variables

Git and other scripts use these "magic" variables to access arguments and process information.

VariablePurpose
$0The name of the script itself.
$1 to $9The 1st through 9th arguments passed to the script.
$#The number of arguments passed.
$@All arguments passed (as a list).
$?The exit status of the last command (0 = Success).
$$The Process ID (PID) of the current script.

IV. Making Scripts Executable

Files are created without execute permissions by default. You must change the mode before running them.

# 1. Create script
touch myscript.sh

# 2. Add content (e.g., echo "Running...")

# 3. Add execute permission for the owner
chmod u+x myscript.sh

# 4. Execute using relative path
./myscript.sh

V. Command Substitution

You can capture the output of a command and store it in a variable using the $(...) syntax.

#!/usr/bin/env bash

# Capture the current date in a specific format
LOG_TIME=$(date "+%Y-%m-%d %H:%M:%S")
USER_COUNT=$(who | wc -l)

echo "[$LOG_TIME] Current users online: $USER_COUNT"

In the next chapter, we'll learn how to direct the flow of data using I/O Redirection and Pipes.