Environment variables configure programs launched from a shell. This guide uses Bash on Linux; CentOS 7 is end-of-life, so use a supported distribution for new systems.
View variables
bash_snippet
Bash · 3 lines|
| printf '%s\n' "$HOME" |
| printenv PATH |
| env |
env lists exported environment variables. The Bash set command also shows shell variables and functions, so it produces more output.Set and remove a variable
bash_snippet
Bash · 3 lines|
| export HELLO="Hello!" |
| printf '%s\n' "$HELLO" |
| unset HELLO |
An exported variable is inherited by child processes, not by the parent shell.
unset removes the variable; assigning an empty string instead leaves it defined. Do not write unset $HELLO, which expands the value instead of naming the variable.To make a variable read-only for the current shell:
bash_snippet
Bash · 2 lines|
| export TEST="example" |
| readonly TEST |
A read-only Bash variable cannot be changed or unset in that shell.
Make settings persistent
For a single user, place exports in the appropriate Bash startup file, such as
~/.bash_profile for login shells or ~/.bashrc for interactive non-login shells. Startup behavior depends on how Bash is invoked. Open a new shell or source the relevant file to load changes in the current shell.For system-wide login-shell settings, an administrator can use an appropriate file under
/etc/profile.d/ or the distribution's existing configuration. Changes affect subsequent sessions; review permissions and existing configuration first.For example, append a directory to
PATH:bash_snippet
Bash · 1 line|
| export PATH="$PATH:/opt/example/bin" |
PATH is case-sensitive. Common variables include HOME, PATH, SHELL, LANG, and LOGNAME; PS1 and HISTSIZE are typically shell variables. Avoid placing secrets in shell startup files or printing them in shared logs.✦ 卷终 · 柯航存卷 ✦