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

482
Visualizações
In bash, should I unset a local variable inside a function?

Should I unset my local variables at the end of a function in a bash script? As an example, the following function:

square()
{
  local var=$1
  (( var = var * var ))
  echo $var
  ## should I unset $var here??
}

Just curious about best practices, thanks!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

If you weren't using the local command, then you would want to unset the variable before leaving the function to avoid polluting the global namespace.

square () {
    var=$1    # var is global, and could be used after square returns
    (( var = var * var ))
    echo $var
    unset var  # Remove it from the global namespace
}

The problem with that approach is that square doesn't know if it actually created var in the first place. It may have overwritten and ultimately unset a global variable that was in use before square was called.

Using local, you are guaranteed to create a new variable that is only visible inside the function. If there were a global var, it's value is ignored for the duration of the function. When the function exits, the local var is discarded, and the global var (if any) can be used as before.

$ var=3
$ echo $var
3
$ square 9
81
$ echo $var
3
over 4 years ago · Santiago Trujillo Relatório

0

If that comment ## should I unset $var here?? is the end of your subroutine, you would not need to unset it, because it would go out of scope right after that anyway.

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