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.
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.
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 .
$() – the command substitution. ${} – the parameter substitution/variable expansion.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With