DEV Community

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

Posted on

2

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs