Session and utilities
The unset command
Removes shell variables or functions, so they no longer exist in the current session.
Most useful options
-vTreats each name as a variable. Without options, it looks for a variable first and, if there is none, for a function with that name.-fTreats each name as a function and removes its definition.-nIf the name is a name reference (nameref), it removes the reference and not the variable it points to. It has no effect with -f.Copy-ready examples
$ export X=1 && unset X && echo "[$X]"deletes the variable and checks that it has no value anymore.Example output
[]
$ saluda() { echo hola; }; unset -f saluda; saludaremoves the function. When you call it, the shell no longer finds it.Example output
bash: saluda: command not found
$ lista=(uno dos tres); unset 'lista[1]'; echo "${lista[@]}"removes only the element at index 1. The single quotes stop the shell from interpreting the brackets.Example output
uno tres
$ dato=7; declare -n ref=dato; unset -n ref; echo "${dato:-vacio}"; echo "[${ref-}]"with -n it removes the reference ref and leaves the variable dato untouched.Example output
7 []
You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| bash: unset: FIJO: cannot unset: readonly variable | The variable was marked read-only with readonly, and the shell does not allow removing it during the session. | There is no way to remove that attribute in the same session: open a new terminal. |
| bash: unset: -q: invalid option | unset has no -q option. It often happens when mixing it up with other commands. | Use unset -v, unset -f or unset -n. The shell help is available with help unset. |
| bash: unset: saluda: cannot unset: readonly function | The function was protected with readonly -f, so unset -f cannot remove it. | Define it again in another session or open a new terminal to start without that protection. |
Typical mistakes
- A read-only variable cannot be removed: unset returns an error and the variable keeps its value.
- Without -f or -v, if there is no variable with that name, unset tries to remove a function. Use -v or -f to be sure.
- An unset inside parentheses or a pipeline only affects that subshell: the parent shell keeps the variable.
Differences from similar commands
FAQ
Is there a difference between X= and unset X?
X= leaves the variable defined with an empty value; unset X removes it completely. With set -u, using an empty variable is fine, but using a removed one is an error.
What happens to the copy child programs receive?
When you unset it, it also leaves the environment passed to the commands you run afterwards.
How do I remove a single array element?
With unset 'name[index]'. If you write unset name without an index, you remove the whole array.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course