Skip to content

Instantly share code, notes, and snippets.

@ryanrichholt
Last active February 18, 2020 19:38
Show Gist options
  • Save ryanrichholt/f9be9dbb7e840d5d4a5e2de866dce468 to your computer and use it in GitHub Desktop.
Save ryanrichholt/f9be9dbb7e840d5d4a5e2de866dce468 to your computer and use it in GitHub Desktop.
Squeaky clean pattern for Bash script with positional arguments
#!/bin/bash
HELP="bestargs.sh <arg1> <arg2> [ <arg3> ...]
Bash script positional arguments can be handled
with simple, one-line-per-argument statements. No
ifs, whiles, exits, or getopts required.
This makes use of some lesser-known parameter expansion
options in bash, :, ?, :-. The examples below are just a
start. In their current form, an empty argument ('') is
treated as if it were not set at all. They could be tweaked
to allow null arguments, or require arguments of minimum
length, for example.
More details found in the bash manual:
http://tldp.org/LDP/abs/html/parameter-substitution.html
"
# Start of example:
ARG1=${1:?"${HELP}Error: arg1 is required"} # Required args will show help, error msg,
ARG2=${2:?"${HELP}Error: arg2 also required"} # and also exit 1 if they are not given.
ARG3=${3:-defaultvalue} # Optional args can have default values
ARG4=${4:-$(whoami)} # Optional arg with a subshell returning the default
ARG57=${@:5:3} # Select a range of args (next three args starting at 5)
ARG8=${8:-arg8defaultvalue} # Another option arg with a default
echo "ARG1: ${ARG1}"
echo "ARG2: ${ARG2}"
echo "ARG3: ${ARG3}"
echo "ARG4: ${ARG4}"
echo "ARG5-7: ${ARG57}"
echo "ARG8: ${ARG8}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment