Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

719
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda