2

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?

1

2 Answers 2

3

Variables are global unless specifically declared to be local.

get_username () {
  local username
  read -p "Enter your username: " username
}
Sign up to request clarification or add additional context in comments.

1 Comment

You probably want -r as well in case someone fat-fingers their username.
0

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;

Comments