DEV Community

Cover image for Mastering Bash arguments with getopts
Hamdy Abou El Anein
Hamdy Abou El Anein

Posted on

Mastering Bash arguments with getopts

In this article, I show you how to mastering the Bash arguments with getopts to have a software who run with professional arguments like

mysoft.bsh -f [arg1] -g [arg2]

I also show you how to add a default value if the argument is not given.

Here's an example of code :

f=10  
g=5  
while getopts ":f:g:" option; do  
    case "${option}" in  
        f)  
            f=${OPTARG}  
            ((f == 15 || f == 75)) || usage  
            ;;  
        g)  
            g=${OPTARG}  
            ;;  
        *)  
            usage
            ;;
    esac  
done  
shift $((OPTIND-1))  
if [ -z "${v}" ] || [ -z "${g}" ]; then  
    echo "info"  
fi  
echo "f = ${f}"  
echo "g = ${g}"

Now we can look at the code more closely :

Here we declare a default value to the variable -v and -g

f=10  
g=5

Here we use getopts with the arguments -f -g. If the user write, software.bsh -f value1 and/or -g value 2.

while getopts ":f:g:" option; do  
    case "${option}" in  
        f)  
            f=${OPTARG}  
            ((f == 15 || f == 75)) || usage  
            ;;  
        g)  
            g=${OPTARG}  
            ;;  
        *)  
            usage
            ;;
    esac  
done

That makes the arguments in Bash more professional.

Image description

Top comments (0)