Skip to main content

Raymii.org Logo (IEC resistor symbol)logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Bash Bits: Simple command line arguments

Published: 30-12-2013 | Author: Remy van Elst | Text only version of this article


Table of Contents


Bash Bits are small examples and tips for Bash Scripts. This bash bit shows youhow to add command line arguments to your script. It is very simple, non-positional and does not use getopts.

If you like this article, consider sponsoring me by trying out a Digital OceanVPS. With this link you'll get $100 credit for 60 days). (referral link)

All Bash Bits can be found using this link

Sometimes a script need to have a variable which you don't know on forehand orcan change later. Or you have a script which works on a file, therefore you needa filename. For example, when you have a script that adds a watermark to animage. It is nice if you can give both the filename and the watermark asparameters to the script.

Note that this is very very simple. The arguments must be given in order and itdoes not support parameters like --file/-f. If you need something quick andsimple, this is very usable, if you need something more advanced it might bebetter to take a look at getopts or shift.

The following example takes one required parameter, and one optional one. If thefirst (filename) is not given, an error message plus usage is printed and thescript exits. A second parameter can be given but is optional. If that is notgiven the script will use the default.

By using the -z option in the if statement, we check if the variable isnull, that is, has zero length.

if [[ -z "${1}" ]]; then    echo -e "[ERROR] Please give a filename to watermark and an optional watermark. Otherwise the default is used."    echo -e "${0} example.jpg"    exit 255else    FILE="${1}"fiif [[ -z "${2}" ]]; then    WATERMARK="Picture Watermark"else    WATERMARK="${2}"fi
Tags: arguments, bash, bash-bits, getopts, parameters, shell, snippets