Blog ≫ 2019 ≫ Bashing out some code

Not done anything like this for a while! Have some code! I did some bash scripting at work this week. We had a script written in javascript 1 meant to run on the command line, but the interactive bit wasn't working. I rewrote it in bash, but found some of the things we take for granted with proper packages then have to be redone from scratch. How do you parse command line arguments in bash? You can use getopts up to a point, but it's not flexible enough. If you want to run a script and have a mix of options like:

myscript -f=flag
    myscript --flag=flag
    myscript -f flag
    myscript --flag flag

and any combo of the above, this is what you need:

while true; do
      case "$1" in
        -f=*|--flag=*) # if we have -f=foo or --flag=foo in our args
          FLAG="${1#*=}" # get just the bit after the =
        ;;
        -f|--flag) # if we have -e foo or --env foo in our args
          shift # past argument
          FLAG="${1}" # get the next arg
        ;;
        '') # if we have no more args
          break
        ;;
        *) # anything else
          echo unknown arg "$1", ignoring >&2
        ;;
      esac
      shift # move on to the next arg
    done
    echo now flag is ${FLAG}

and then duplicate the -f --flag stuff for each param...

Also while I'm here this is handy and gets a place in all my future bash scripts:

trap cleanup SIGINT SIGTERM
    cleanup () {
      echo 🚯 here is where I do all my tidying up
      # killall etc here
    }
    cleanup || true

As you were.

  1. Programming language of the web, mostly how I make my living.

⬅️ :: ➡️

Paulʼs blog - I live in A sleepy town in the far South. Married + father to two, I am a full-stack web developr, and I do js / node, some ruby, python, php ect ect. My hobbies are pubs, parkrun, restaurants, home automation 🤖 + other diy jiggery-pokery, history, family tree stuff, telly, squirrels, pirates ☠️, lego, and TIME TRAVEL.