刪除指定的shell變量或函數(shù)。
unset [-f] [-v] [-n] [name ...]
-f:僅刪除函數(shù)。
-v:僅刪除變量(不包括只讀變量)。
-n:刪除具有引用屬性的變量名(如果該選項存在)。
name(可選):要刪除的變量或函數(shù)。
返回成功除非選項錯誤或要刪除的變量或函數(shù)有只讀屬性。
# 刪除變量。
declare paper_size='B5'
unset -v paper_size
# 刪除函數(shù)。
function show_result(){ echo 'Last Command Return: $?'; }
unset -f show_result
# 當不指定選項時,優(yōu)先刪除變量,如果失敗則刪除函數(shù)。
declare -i aa=100
function aa(){ echo 'aa'; }
unset aa
# 變量'aa'已被刪除。
declare -p aa
# 函數(shù)'aa'存在。
declare -F|grep aa
# 演示unset使用-n選項,name指定了引用變量時的情況。
declare a=3
# 定義引用變量
declare -n b=a
# 查看屬性,顯示declare -n b="a"
declare -p b
# 顯示3
echo ${b}
# 顯示a
echo ${!b}
# 指定-n選項時
unset -n b
# 引用變量b已被刪除
declare -p b
# 被引用的變量a未被刪除
declare -p a
# 演示unset不使用-n選項,name指定了引用變量時的情況。
declare a=3
# 定義引用變量
declare -n b=a
# 查看屬性,顯示declare -n b="a"
declare -p b
# 顯示3
echo ${b}
# 顯示a
echo ${!b}
# 不指定-n選項時
unset b
# 引用變量b未被刪除,顯示declare -n b="a"
declare -p b
# 被引用的變量a被刪除
declare -p a
help
命令。