TUTORIAL 7 • INTERMEDIATE

Start shell scripting with Bash

Shell scripts turn repeatable command-line work into repeatable programs. Start with small scripts and make their inputs, outputs and failure behavior explicit.

Variables and quoting

#!/usr/bin/env bash
name="Linux learner"
printf 'Hello, %s\n' "$name"

Quote variable expansions by default. This prevents spaces and many special characters from being interpreted as separate shell words.

Conditions and loops

if [ -f "notes.txt" ]; then
  echo "notes.txt exists"
fi

for item in one two three; do
  echo "$item"
done

Arguments and exit status

#!/usr/bin/env bash
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 NAME" >&2
  exit 2
fi
printf 'Hello, %s\n' "$1"
exit 0

$# counts arguments, $1 is the first argument, and the exit status communicates success or failure to the calling shell.

Good habit: Make a script do one small job first. Test expected input, quote data, and return meaningful exit codes before adding complexity.
← Back to all tutorials