8

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.

1

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.