Make a Shell Script with Arguments (Native)

I was building a bash script and I needed several arguments to make it more versatile (e.g. dry-run). The list of parameters was:

  • help as -h or --help
  • dry run ad -d or --dry-run to go through the motions without actually executing commands
  • keep last N images ad -k num or --keep num to keep last N images (default 5)

As one can see, none of the parameters are compulsory and have default values:

The snipped taking care of my input parameters is:

The idea is that we loop through all script arguments and shift accordingly. Since the parameters are space separated, we shiftonce for flags without parameters (e.g. --help) and twice for flags with parameters (e.g. --keep).

Once the input parameters are processed, all variables are initialised accordingly.

Note: If you have compulsory parameters, you’ll need to check their presence (e.g. via a variable initialised empty) before further processing.


It’s good to add a help function. Some languages like python have arguments modules with advanced processing and generate help information by default. Unfortunately, the exclusive-shell variant doesn’t do that (unless you want to over-engineer) and you need to do it manually. I ended up having a function like:

This function can be called from the shell processor:

A little experiment: If you find this post and ad below useful, please check the ad out :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top