0 Preface
Today, when writing a shell script to read the environment variable, I found that the cancellation of the environment variable has not taken effect. Record the solution for future reference.
1. Questions
First the script is as follows:
Get the environment variable JAVA_HEAP_XMX
and JAVA_HEAP_XMN
finally print it out, if the environment variable is empty, print the default value
#!/usr/bin/env bash
# 指定堆内存
HEAP_XMX="2g"
HEAP_XMN="512m"
if [ -n "$JAVA_HEAP_XMX" ]; then
HEAP_XMX=${JAVA_HEAP_XMX}
fi
if [ -n "$JAVA_HEAP_XMN" ]; then
HEAP_XMN=${JAVA_HEAP_XMN}
fi
echo "堆内存大小: ${HEAP_XMX}"
echo "堆内存年轻代大小: ${HEAP_XMN}"
/etc/profile
Environment variables are configured in the file :
export JAVA_HEAP_XMX=3g
export JAVA_HEAP_XMN=1g
After source /etc/profile
reloading the environment variable, execute the script, and find out that the acquisition was successful through the output.
But when we cancel the environment variable
We found that the previous environment variable value was still loaded, which means that the environment variable we deleted did not take effect
Why is this?
2. Solve
In fact, it goes back to source
the loading principle of the instruction. The source loads the environment variables configured in the file into the cache, but because the environment variables are deleted, the source is actually not obtained when it is obtained, and the cache will not be updated. .
So if we want to delete environment variables separately, we also need to use unset
instructions
unset JAVA_HEAP_XMX
unset JAVA_HEAP_XMN
After execution, our environment variable is canceled from the cache, and the above script prints the default value
3. Summary
To cancel the environment variable, in addition to modifying /etc/profile
the file, unset 环境变量名
delete the environment variable cache by