Blog2019 ≫ 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 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.

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

⬅️ :: ➡️

Paul Clarke's weblog - I live in A small town. Wed and dad to two, I am a full-stack web developr, + I do mostly javascript / nodejs, some ruby, other languages ect ect. I like pubs, parkrun, eating, home-automation and other diy jiggery-pokery, history, genealogy, Television, squirrels, pirates, lego, and time travel.