stackademic

The leading education platform for anyone with an interest in software development.

Shell Scripting Basics

Automate tasks by writing reusable scripts in Bash

Overview

A shell script is just a file containing commands you'd otherwise type by hand, saved so you can run them repeatedly. Scripts can take arguments, make decisions with conditionals, and loop over lists, turning manual chores into one command. Bash scripting is the natural next step once you're comfortable with individual commands.

Syntax / Usage

Start with a shebang line, then use variables, conditionals, and loops.

#!/usr/bin/env bash
set -euo pipefail          # exit on errors and undefined variables

NAME="$1"                  # first argument passed to the script

if [ -z "$NAME" ]; then
  echo "Usage: greet.sh <name>"
  exit 1
fi

for i in 1 2 3; do
  echo "Hello $NAME ($i)"
done

Examples

A tiny script that greets a name passed as an argument:

#!/usr/bin/env bash
echo "Hello, ${1:-world}!"

Loop over files and report their line counts:

#!/usr/bin/env bash
for file in *.txt; do
  echo "$file: $(wc -l < "$file") lines"
done

Make the script runnable and execute it:

chmod +x greet.sh
./greet.sh Alice

Common Mistakes

  • Omitting the shebang line, so the wrong interpreter runs the script
  • Forgetting to chmod +x the file before running it
  • Leaving variables unquoted, which breaks on paths with spaces
  • Skipping set -euo pipefail, so errors pass silently
  • Putting spaces inside [ ] incorrectly, e.g. [$x] instead of [ "$x" ]

See Also

command-line-permissions command-line-environment-variables command-line-text-processing