Removing Variables with unset
The unset built-in command removes a variable (or a function) from the current shell. After unset, the name no longer exists: Bash does not keep an empty value behind, it forgets the name completely. This lesson explains what removal means, how it differs from assigning an empty string, and where unset has limits.
Syntax
unset NAME # remove a variable
unset NAME1 NAME2 # remove several names at once
unset -v NAME # remove a variable only (never a function)
unset -f NAME # remove a function only
unset 'array[index]' # remove one element of an array
Give unset the name of the variable, without a dollar sign. unset city is correct. unset $city is a different command, which is explained near the end of this lesson.
Removing a Variable
cat > u1.sh <<'EOF'
city=Paris
echo "before: city=$city"
unset city
echo "status of unset: $?"
echo "after: city=[$city]"
unset nothing_here
echo "unset of a name that does not exist: status=$?"
EOF
bash u1.sh
before: city=Paris
status of unset: 0
after: city=[]
unset of a name that does not exist: status=0
The script creates city, removes it, and reads it again. Reading a removed variable gives an empty string, just as reading any variable that was never set does. Notice two details about the exit status:
- A successful
unsetreturns0. - Removing a name that does not exist also returns
0.unsetis not an error check, so you cannot use it to find out whether a variable existed.
Unset Is Different from Empty
A variable can be in one of two situations that look the same when you print it:
- Set to an empty value: the name exists and holds
"". - Unset: the name does not exist at all.
Most of the time you will not notice the difference, but some tools do. The test [[ -v NAME ]] is true when the name exists, even if the value is empty:
cat > u2.sh <<'EOF'
empty=""
unset gone
[[ -v empty ]] && echo "empty is set (value is empty)" || echo "empty is unset"
[[ -v gone ]] && echo "gone is set" || echo "gone is unset"
echo "${empty-DEFAULT}|${gone-DEFAULT}"
echo "${empty:-DEFAULT}|${gone:-DEFAULT}"
declare -p empty
declare -p gone
echo "declare -p status for gone: $?"
EOF
bash u2.sh
empty is set (value is empty)
gone is unset
|DEFAULT
DEFAULT|DEFAULT
declare -- empty=""
u2.sh: line 8: declare: gone: not found
declare -p status for gone: 1
Reading the output line by line:
[[ -v empty ]]is true, becauseemptyexists.[[ -v gone ]]is false.${name-DEFAULT}(with no colon) uses the default only when the variable is unset. It printed nothing foremptyandDEFAULTforgone. The two outputs are separated by|.${name:-DEFAULT}(with a colon) uses the default when the variable is unset or empty, so both gaveDEFAULT. Lesson 45 covers these forms in detail.declare -pprints a variable together with its attributes. It confirms thatemptyexists and fails with status1for a name that does not.
So name="" empties a variable, while unset name removes it.
Removing Several Variables
List as many names as you like. Every name is removed, and the others are not touched:
cat > u3.sh <<'EOF'
A=1 B=2 C=3
unset A B
echo "A=[$A] B=[$B] C=[$C]"
unset -v C
echo "C=[$C]"
EOF
bash u3.sh
A=[] B=[] C=[3]
C=[]
The -v option says "treat this name as a variable". It is the default behavior, so unset C and unset -v C do the same thing, but writing -v makes the intent obvious.
Removing Variables That Share a Prefix
Bash can expand ${!PREFIX@} into the names of all variables that start with PREFIX. Combined with unset, this removes a whole family of settings in one command:
cat > v11.sh <<'EOF'
APP_A=1 APP_B=2 APP_C=3 OTHER=9
unset "${!APP_@}"
echo "APP_A=[${APP_A-<unset>}] OTHER=[$OTHER]"
EOF
bash v11.sh
APP_A=[<unset>] OTHER=[9]
The expansion produced APP_A APP_B APP_C, and unset removed all three. OTHER does not start with APP_, so it stayed.
Removing Functions with unset -f
A function is also a named item in the shell, and unset -f removes it:
cat > u4.sh <<'EOF'
greet() { echo "hello"; }
greet
unset -f greet
greet
echo "status=$?"
type greet
EOF
bash u4.sh
hello
u4.sh: line 4: greet: command not found
status=127
u4.sh: line 6: type: greet: not found
After unset -f greet, the name is gone, so Bash reports command not found with the status 127 (the status for an unknown command).
A variable and a function can share one name. In that case the options decide which one is removed:
cat > u5.sh <<'EOF'
thing=var
thing() { echo "function thing"; }
unset thing
echo "var after plain unset: [$thing]"
thing
unset -f thing
type thing 2>&1
EOF
bash u5.sh
var after plain unset: []
function thing
u5.sh: line 7: type: thing: not found
A plain unset thing removes the variable first, so the function survived and still ran. When there is no variable with that name, a plain unset removes the function instead. Use -v or -f whenever the distinction matters, so the command removes exactly what you mean.
Removing Array Elements
Quote the element reference so that Bash does not treat the square brackets as a filename pattern:
cat > v2.sh <<'EOF'
fruits=(apple banana cherry)
unset 'fruits[1]'
echo "elements: ${fruits[@]}"
echo "count: ${#fruits[@]}"
echo "indices: ${!fruits[@]}"
unset fruits
echo "after: count=${#fruits[@]}"
EOF
bash v2.sh
elements: apple cherry
count: 2
indices: 0 2
after: count=0
Removing fruits[1] leaves a gap: the remaining elements keep their original indices 0 and 2. They are not renumbered. Removing the name fruits without an index deletes the entire array. Later lessons on arrays return to this behavior.
Unset and Exported Variables
An exported variable travels into every program the shell starts. Removing it in the shell stops it from being passed on:
cat > u8.sh <<'EOF'
export LEVEL=debug
bash -c 'echo "child 1 sees: [$LEVEL]"'
unset LEVEL
bash -c 'echo "child 2 sees: [$LEVEL]"'
EOF
bash u8.sh
child 1 sees: [debug]
child 2 sees: []
This is the clean way to stop a setting from reaching later commands. Note the direction: unset in a child process never changes the parent, because each process has its own copy of its variables.
Unset Inside Functions and Subshells
Inside a function, what unset removes depends on how the variable was created.
A variable made with local belongs to the function. Removing it inside the function does not touch a global variable of the same name:
cat > v3.sh <<'EOF'
x=global
f() {
local x=inner
unset x
echo "in f after unset: [${x-<unset>}]"
}
f
echo "outside: [$x]"
EOF
bash v3.sh
in f after unset: [<unset>]
outside: [global]
A function can also remove a global variable, when no local variable hides it:
cat > v4.sh <<'EOF'
mode=fast
reset() { unset mode; }
reset
echo "mode=[${mode-<unset>}]"
EOF
bash v4.sh
mode=[<unset>]
A subshell, written with parentheses, works on a copy of the shell. Removing a variable in it leaves the original untouched:
cat > v5.sh <<'EOF'
name=Ana
( unset name; echo "inside subshell: [${name-<unset>}]" )
echo "outside: [$name]"
EOF
bash v5.sh
inside subshell: [<unset>]
outside: [Ana]
Why unset $name Is Not the Same as unset name
Bash expands $name into its value before it runs the command. So unset $target does not remove target. It removes the variable whose name is stored inside target:
cat > u6.sh <<'EOF'
target=color
color=blue
unset $target
echo "color=[$color] target=[$target]"
EOF
bash u6.sh
color=[] target=[color]
The shell turned unset $target into unset color. The variable target itself still holds the text color. Unless you really want this indirect behavior, always write the plain name.
Unset Variables and set -u
When the set -u option is on (covered in a later lesson), reading a variable that does not exist is a fatal error:
cat > u7.sh <<'EOF'
set -u
token=abc
unset token
echo "about to read token"
echo "$token"
echo "never printed"
EOF
bash u7.sh
about to read token
u7.sh: line 5: token: unbound variable
The script stopped with exit status 1 at the line that read token. To read a variable that might be unset without triggering the error, give it a default value:
cat > v7.sh <<'EOF'
set -u
token=abc
unset token
echo "safe read: [${token-}]"
echo "with default: [${token:-none}]"
EOF
bash v7.sh
safe read: []
with default: [none]
Variables That Cannot Be Removed
A variable marked with readonly cannot be removed. unset prints an error and returns status 1:
cat > u9.sh <<'EOF'
readonly LIMIT=10
unset LIMIT
echo "status=$? LIMIT=$LIMIT"
EOF
bash u9.sh
u9.sh: line 2: unset: LIMIT: cannot unset: readonly variable
status=1 LIMIT=10
This is the same message that lesson 40 showed. The read-only attribute protects the variable until the shell ends.
Removing Important Built-In Variables
Bash lets you remove variables that it uses itself, and the consequences are real. Removing PATH means Bash can no longer search for commands by name:
cat > v6.sh <<'EOF'
unset PATH
ls
echo "status=$?"
/bin/echo "full path still works"
EOF
bash v6.sh
v6.sh: line 2: ls: No such file or directory
status=127
full path still works
Commands that are built into Bash still work, and so do commands called with a full path. Everything else fails with status 127. Because the change lasts only for the current shell, closing the shell or starting a new one restores PATH, but do not remove variables such as PATH, HOME or IFS in a script unless you have a clear reason.
Practical Example: Resetting Configuration
A script that reads settings from the environment sometimes needs to clear its own settings before it loads a new set. This keeps old values from leaking into the next run:
cat > reset.sh <<'EOF'
export APP_ENV=prod
APP_DEBUG=1
APP_PORT=8080
echo "before: $(env | grep -c '^APP_ENV=')"
unset APP_ENV APP_DEBUG APP_PORT
echo "after: $(env | grep -c '^APP_ENV=')"
echo "APP_PORT=[${APP_PORT-<unset>}]"
EOF
bash reset.sh
before: 1
after: 0
APP_PORT=[<unset>]
The env | grep -c command counts how many lines of the environment begin with APP_ENV=. Before unset there is one such line, afterwards none. APP_DEBUG and APP_PORT were never exported, but unset removes ordinary variables in exactly the same way, which is why listing all three names is safe.