Script Parameters

Learn how to change the Bash script's behavior using parameters.

Parametrizing the photo directory

Let’s suppose we moved our photos from the ∼/photo directory to ∼/Documents/Photo. If we want to support the new path in the backup script, we should change its code. The following shows how the new script looks:

#!/bin/bash

tar -cjf ~/photo.tar.bz2 ~/Documents/Photo &&
  echo "tar - OK" > results.txt ||
  { echo "tar - FAILS" > results.txt ; exit 1 ; }

cp -f ~/photo.tar.bz2 ~/backup &&
  echo "cp - OK" >> results.txt ||
  ! echo "cp - FAILS" >> results.txt

Every time we move the photos from one directory to another, we have to change the script. This is inconvenient. A better solution is to make a universal script that can handle any directory. Such a script would receive the path to photos as an input parameter.

When we run a Bash script, we can pass command-line parameters there. This works the same way as for any GNU utility. We specify the parameters separated by a space after the script name. Bash will pass them to the script. Here is an example:

./photo-backup.sh ~/Documents/Photo

This command runs our script with the ...