mdurban
mdurban

Reputation: 119

How do I pass in optional flags and parameters to bash script?

I have a bash script that I pass parameters into (and access via $1). This parameter is a single command that must be processed (i.e. git pull, checkout dev, etc.).

I run my script like ./script_name git pull

Now, I want to add an optional flag to my script to do some other functionality. So if I call my script like ./script_name -t git pull it will have a different functionality from ./script_name git pull.

How do I access this new flag along with the parameters passed in. I've tried using getopts, but can't seem to make it work with the other non-flag parameters that are passed into the script.

Upvotes: 8

Views: 12698

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

Using getopts is indeed the way to go:

has_t_option=false
while getopts :ht opt; do
    case $opt in 
        h) show_some_help; exit ;;
        t) has_t_option=true ;;
        :) echo "Missing argument for option -$OPTARG"; exit 1;;
       \?) echo "Unknown option -$OPTARG"; exit 1;;
    esac
done

# here's the key part: remove the parsed options from the positional params
shift $(( OPTIND - 1 ))

# now, $1=="git", $2=="pull"

if $has_t_option; then
    do_something
else
    do_something_else
fi

Upvotes: 14

Related Questions