Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

718
Views
Bash script with both parameter values and optional flags

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!