unset
Remove shell variables
TLDR
Remove the variable foo, or if the variable doesn't exist, remove the function foo
Remove the variables foo and bar
Remove the function my_func
SYNOPSIS
unset [-fv] name ...
PARAMETERS
-f
Treat each name as a function name. This option explicitly tells unset to look for and remove functions, even if a variable with the same name exists.
-v
Treat each name as a variable name. This is the default behavior if neither -f nor -v is specified. It ensures variables are removed.
DESCRIPTION
The unset command is a shell built-in used to remove variables or functions from the current shell's environment. When a variable is unset, its value is cleared, and it effectively ceases to exist within that shell's scope. Similarly, unsetting a function removes its definition, making it unavailable for execution. This is crucial for managing the shell's memory, cleaning up temporary data, and ensuring that sensitive or outdated information stored in variables is cleared. Variables that have been exported will also be removed from the environment passed to child processes launched subsequent to the unset command.
CAVEATS
Read-only Variables: Variables declared with readonly cannot be unset. Attempting to do so will result in an error and a non-zero exit status.
Special Shell Parameters: Many special shell parameters (e.g., $$ (process ID), $? (exit status), $0 (script name), $# (argument count), $@ (all arguments)) cannot be unset as they are dynamically managed by the shell itself.
Non-existent Names: If you attempt to unset a variable or function that does not exist, unset typically returns a non-zero exit status (failure) but usually does not produce an error message unless in strict shell modes.
<I>EXIT STATUS</I>
The unset command typically returns an exit status of 0 (success) unless an invalid option is given or a read-only variable is specified for unsetting. If a variable or function to be unset does not exist, unset generally returns a non-zero exit status (failure) but does not print an error message by default.
<I>SCOPE CONSIDERATIONS</I>
Unsetting a variable or function affects only the current shell environment. It does not impact parent shells or other concurrently running shells. If a variable was exported, its removal will prevent it from being inherited by *new* child processes launched from the current shell after the unset command is executed.
HISTORY
The unset command is a fundamental built-in command present in all Bourne-like shells, including sh, bash, ksh, and zsh. Its core functionality has remained consistent since its introduction, providing a direct way to manage the shell's active variables and functions. It is an indispensable part of shell scripting for environment management and cleanup tasks.