Bash Scripting Basics
Turn a sequence of commands into a reusable, parameterized script.
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.
#!/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. - Write a script that takes a filename argument and prints its line count.
- Add a check that exits with a message if no argument is given.
- Use command substitution to embed the current hostname in the output.
- Print the script’s own name using
$0and the number of args using$#.
Cheat Sheet▾
| Item | Syntax |
|---|---|
| Shebang | #!/usr/bin/env bash |
| Variable | x="value" → $x |
| Command substitution | $(cmd) |
| Arguments | $1 $2 $@ $# |
| Exit code of last cmd | $? |
| Make executable | chmod +x script.sh |
| Exit with status | exit 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)".