Bash Scripting Basics

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Bash

Bash Scripting Basics

Beginner ⭐ 50 XP ⏱ 18 min #bash#scripting

Turn a sequence of commands into a reusable, parameterized script.

📖Theory

A Bash script is just a text file of commands the shell runs top to bottom. It starts with a shebang (#!/usr/bin/env bash) that names the interpreter, and you make it runnable with chmod +x.

The building blocks: variables (name="value", used as $name), command substitution ($(command) captures output), arguments ($1, $2, $@), and exit codes ($?, where 0 means success). Always quote variables — "$var" — to avoid word-splitting bugs.

🌍Real-World Example
#!/usr/bin/env bash
# greet.sh — say hello to a named user

name="$1"                       # first argument
if [ -z "$name" ]; then         # is it empty?
  echo "Usage: $0 <name>"
  exit 1
fi

today="$(date +%F)"             # command substitution
echo "Hello, $name! Today is $today."
chmod +x greet.sh
./greet.sh Alex                 # Hello, Alex! Today is 2026-06-22.
✍️Hands-On Exercise
  1. Write a script that takes a filename argument and prints its line count.
  2. Add a check that exits with a message if no argument is given.
  3. Use command substitution to embed the current hostname in the output.
  4. Print the script’s own name using $0 and the number of args using $#.
🧾Cheat Sheet
ItemSyntax
Shebang#!/usr/bin/env bash
Variablex="value"$x
Command substitution$(cmd)
Arguments$1 $2 $@ $#
Exit code of last cmd$?
Make executablechmod +x script.sh
Exit with statusexit 1
💬Common Interview Questions
What does the shebang line do?

It tells the OS which interpreter should run the script. The kernel reads the first line and executes that program with the script as its argument.

Why quote variables in Bash?

Unquoted variables undergo word-splitting and globbing, so a value with spaces or wildcards breaks commands. “$var” preserves it as a single literal argument.

How do you capture a command's output into a variable?

Command substitution: result="$(command)".

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type