Monday, February 21, 2022

[SOLVED] Bash script with both parameter values and optional flags

Issue

I'm writing a bash script, which relies on a number of values provided via parameters and offers optional (boolean) flags.

Based on the example on href="https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script" rel="nofollow noreferrer">this page, I've extended the script, with the -h option, the to the following:

human=false

while getopts u:a:f:h: flag
do
    case "${flag}" in
        u) username=${OPTARG};;
        a) age=${OPTARG};;
        f) fullname=${OPTARG};;
        h) human=true;;
    esac
done

if $human; then
        echo "Hello human"
else
        echo "You're not human"
fi

echo "Username: $username";
echo "Age: $age";
echo "Full Name: $fullname";

The problem with this is, the -h parameter requires a value, whereas it should be handles as a flag:

bash test.sh -u asdf -h
test.sh: option requires an argument -- h
You're not human
Username: asdf
Age: 
Full Name: 

How can I use both parameters with values and flags in a bash script?


Solution

You should replace getopts u:a:f:h: with getopts u:a:f:h.

Removing the : you tell getopts that h has no additional argument.



Answered By - Antonio Petricca
Answer Checked By - Candace Johnson (WPSolving Volunteer)