Skip to content
Advertisement

Bash Shell Script – Check for a flag and grab its value

I am trying to make a shell script which is designed to be run like this:

script.sh -t application

Firstly, in my script I want to check to see if the script has been run with the -t flag. For example if it has been run without the flag like this I want it to error:

script.sh

Secondly, assuming there is a -t flag, I want to grab the value and store it in a variable that I can use in my script for example like this:

FLAG="application"

So far the only progress I’ve been able to make on any of this is that $@ grabs all the command line arguments but I don’t know how this relates to flags, or if this is even possible.

Advertisement

Answer

You should read this getopts tutorial.

Example with -a switch that requires an argument :

#!/bin/bash

while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    ?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

Like greybot said(getopt != getopts) :

The external command getopt(1) is never safe to use, unless you know it is GNU getopt, you call it in a GNU-specific way, and you ensure that GETOPT_COMPATIBLE is not in the environment. Use getopts (shell builtin) instead, or simply loop over the positional parameters.

Advertisement