Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

720
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda