The unset command in Bash is used to remove variable and function name bindings. Essentially, it deletes a variable or function from the shell's memory.
What it does:
- Variables: When used with a variable name,
unset removes the variable from the environment. After unset, attempting to use the variable will result in it being treated as if it was never defined (it will expand to an empty string).
- Functions: When used with a function name,
unset removes the function definition. After unset, attempting to call the function will result in a "command not found" error.
Arguments it can take:
unset takes one or more arguments, each representing the name of a variable or function to remove. The arguments are space-separated.
Example:
my_variable="hello"
echo $my_variable # Output: hello
unset my_variable
echo $my_variable # Output: (empty string)
my_function() {
echo "This is my function"
}
my_function # Output: This is my function
unset my_function
my_function # Output: bash: my_function: command not found
What happens with wrong arguments:
-
Non-existent variable/function: If you try to unset a variable or function that doesn't exist, unset doesn't produce an error. It simply does nothing. It's not an error to try to remove something that isn't there.
unset non_existent_variable # No error message
-
Invalid characters in name: If the argument contains characters that are not valid in a variable or function name (e.g., !, $, &, etc.), Bash will usually report a syntax error.
unset my!variable # bash: unset: my!variable: invalid name
Too many arguments:
unset can handle multiple arguments at once. There's no practical limit to the number of arguments you can provide, as long as each argument is a valid variable or function name.
a="1"
b="2"
c="3"
unset a b c
echo $a # (empty string)
echo $b # (empty string)
echo $c # (empty string)
Important Notes:
unset only affects the current shell session. If you want to permanently remove a variable, you need to modify the shell's configuration file (e.g., .bashrc, .bash_profile).
unset does not affect environment variables that were inherited from the parent process. To remove those, you'd need to use export -n variable_name.
unset does not affect aliases. Use unalias to remove aliases.
In summary, unset is a straightforward command for removing variable and function definitions from your current Bash session. It's a useful tool for cleaning up your environment and ensuring that variables and functions don't interfere with your scripts or other processes.