Joel Hoelting
Joel Hoelting

Reputation: 1992

Store local variable from user input in bash?

When getting user input via the read command and storing in a variable. For example:

get_username() {
  read -p "Enter your username: " username
}

another_function() {
  echo $username
}

get_username; another_function;

The $username variable is now available globally within the entire script. Is there a way to restrict the scope of the variable stored from the user input or delete it after it is no longer needed?

Upvotes: 2

Views: 1633

Answers (2)

JustAnotherProgrammer
JustAnotherProgrammer

Reputation: 146

you can use unset to unset the variable or local to limit the visibility

get_username() {
  read -p "Enter your username: " username
}

another_function() {
  echo $username
  unset username

}

get_username; another_function; another_function;

Upvotes: 1

chepner
chepner

Reputation: 530960

Variables are global unless specifically declared to be local.

get_username () {
  local username
  read -p "Enter your username: " username
}

Upvotes: 4

Related Questions