1

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 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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What would I do if I have more than one boolean flag? So both an -h and a -d that neither need args only change the default false to a true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.