Removing Variables with unset

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 41 of 205

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 unset returns 0.
  • Removing a name that does not exist also returns 0. unset is 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:

  1. [[ -v empty ]] is true, because empty exists. [[ -v gone ]] is false.
  2. ${name-DEFAULT} (with no colon) uses the default only when the variable is unset. It printed nothing for empty and DEFAULT for gone. The two outputs are separated by |.
  3. ${name:-DEFAULT} (with a colon) uses the default when the variable is unset or empty, so both gave DEFAULT. Lesson 45 covers these forms in detail.
  4. declare -p prints a variable together with its attributes. It confirms that empty exists and fails with status 1 for 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Removing Variables with unset and get answers drawn from it.

Signed-in readers only.