Menu
CoddyTech

Checking Arguments

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 4 of 39.

A script that runs with the wrong number of arguments does the wrong thing quietly. Check $# at the top, and stop with a usage line that shows how to call the script.

#!/bin/bash
if [ $# -ne 2 ]; then
  echo "Usage: backup.sh SOURCE COPY" >&2
  exit 1
fi
cp "$1" "$2"
echo "Copied $1 to $2"

-ne means not equal. >&2 sends the line to standard error (stderr), the stream for error messages. It still shows in the terminal, but it stays out of the output a pipe or a > file collects. exit 1 stops the script before the cp and reports a failure.

bash backup.sh notes.txt; echo "exit $?"

This prints Usage: backup.sh SOURCE COPY and exit 1. With 2>/dev/null added after notes.txt, the usage line disappears and only exit 1 is left. With two arguments, the check is skipped and the copy runs.

challenge icon

Challenge

Medium

Write a script that moves a file into a folder, and refuses to run with the wrong number of arguments.

  1. Open move.sh. It takes a file as the first argument and a folder as the second.
  2. If the number of arguments is not exactly 2, print Usage: move.sh FILE FOLDER to stderr and exit with code 1.
  3. Otherwise, move the file into the folder with mv and print Moved FILE to FOLDER.
  4. Save the file.

Try it: run bash move.sh report.txt archive. It prints:

Moved report.txt to archive

Then run bash move.sh photo.jpg; echo "exit $?" with the folder missing. It prints:

Usage: move.sh FILE FOLDER
exit 1

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground