Shell Scripting Basics

Advanced

Overview

A script starts with a shebang like #!/usr/bin/env bash and is run after chmod +x. Variables are assigned without spaces (NAME=value) and referenced with $NAME.

Conditionals use if [ ... ]; then ... fi, and loops use for x in ...; do ... done. Always quote your variables ("$VAR") to avoid word-splitting surprises.

Add set -euo pipefail near the top to make scripts fail fast on errors and undefined variables — a best practice for reliable automation.

Cheatsheet

#!/usr/bin/env bashShebang line
set -euo pipefailSafer script defaults
NAME="world"Assign a variable (no spaces)
echo "Hello $NAME"Use a variable
for f in *.log; do …; doneLoop over files
if [ -f f ]; then …; fiRun only if the file exists

Try it

A safe, simulated terminal. Run the suggested commands to see typical output.

simulated terminal

Type a command and press Enter, or click a suggestion below to run it.

$

Quick quiz

1. What does `set -e` do in a bash script?

2. How do you reference a variable named NAME?