TrumanWong

unset

Delete the specified shell variable or function.

Summary

unset [-f] [-v] [-n] [name ...]

The main purpose

  • Delete one or more shell variables (excluding read-only variables).
  • Delete one or more shell functions.
  • Remove one or more variables with reference attributes (if the -n option is present).

Options

-f: Remove functions only.
-v: Delete variables only (excluding read-only variables).
-n: Remove variable names with reference attributes (if this option exists).

Parameters

name (optional): The variable or function to delete.

return value

Returns successful unless the option is wrong or the variable or function to be deleted has a read-only attribute.

example

# Delete variables.
declare paper_size='B5'
unset -v paper_size
# Delete function.
function show_result(){ echo 'Last Command Return: $?'; }
unset -f show_result
# When no option is specified, variables are deleted first, and functions are deleted if failed.
declare -i aa=100
function aa(){ echo 'aa'; }
unset aa
# Variable 'aa' has been deleted.
declare -p aa
# Function 'aa' exists.
declare -F|grep aa
# Demonstrate unset using the -n option, and name specifies the situation when the variable is referenced.
declare a=3
#Define reference variables
declare -n b=a
# Check the attributes and display declare -n b="a"
declare -p b
# show 3
echo ${b}
# show a
echo ${!b}
# When specifying the -n option
unset -n b
# The reference variable b has been deleted
declare -p b
#The referenced variable a has not been deleted
declare -p a
# Demonstrate that unset does not use the -n option, and name specifies the situation when the variable is referenced.
declare a=3
#Define reference variables
declare -n b=a
# Check the attributes and display declare -n b="a"
declare -p b
# show 3
echo ${b}
# show a
echo ${!b}
# When -n option is not specified
unset b
# The reference variable b has not been deleted, and declare -n b="a" is displayed.
declare -p b
#The referenced variable a is deleted
declare -p a

Notice

  1. This command is a built-in bash command. For related help information, please see the help command.