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
MediumWrite a script that moves a file into a folder, and refuses to run with the wrong number of arguments.
- Open
move.sh. It takes a file as the first argument and a folder as the second. - If the number of arguments is not exactly 2, print
Usage: move.sh FILE FOLDERto stderr and exit with code1. - Otherwise, move the file into the folder with
mvand printMoved FILE to FOLDER. - Save the file.
Try it: run bash move.sh report.txt archive. It prints:
Moved report.txt to archiveThen run bash move.sh photo.jpg; echo "exit $?" with the folder missing. It prints:
Usage: move.sh FILE FOLDER
exit 1Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground