Search code examples
bashshellcommand-line-argumentsflagsgetopt

Check for flag passed to a Bash script and process value


I have a bash script in which I want to check if a flag with value was passed to it and then use the value in a variable. Something like this (pseudocode):

file.sh -c 1.0.0

inside file.sh :

#!/bin/bash

get flag:
if flag 'c' then 
curl c
else 
curl 'something else'

Whats the most optimal way to do the above?


Solution

  • try the following

    #!/bin/bash
    
    
    while getopts ":c" opt; do
     case $opt in
     c)
        echo "-c was triggered!" >&2
        ;;
     \?)
        echo "Invalid option: -$OPTARG" >&2
        ;;
     esac
    done