Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 631
Jimmy Avatar asked Jan 21 '13 21:01

Jimmy


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is flag in bash script?

flag is the iterator variable here. In bash the do followed by while statement specifies starting of block which contains satement to be executed by while . The ending of block is specified by done .

What does $() mean in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.


2 Answers

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.

like image 127
Gilles Quenot Avatar answered Oct 03 '22 11:10

Gilles Quenot


Use $# to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:

if [ $# -ne 2 ]; then    usage; fi 

Next, check if $1 equals -t, otherwise an unknown flag was used:

if [ "$1" != "-t" ]; then   usage; fi 

Finally store $2 in FLAG:

FLAG=$2 

Note: usage() is some function showing the syntax. For example:

function usage {    cat << EOF Usage: script.sh -t <application>  Performs some activity EOF    exit 1 } 
like image 36
Veger Avatar answered Oct 03 '22 10:10

Veger