Environment variables are often used to store a list of paths of where to search for executables, libraries, and so on.
環境變量通常存放一堆路徑,這些路徑用來搜索可執行文件、動態鏈接庫,等等。
Examples are $PATH, $LD_LIBRARY_PATH, 可以通過 echo 命令來查看:
[root@localhost ~]# echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/opt/ruby/bin:/root/bin:/opt/python36/bin [root@localhost ~]#
在終端命令行中輸入命令或可執行文件的文件名,系統會去$PATH定義的環境變量里的逐個去查找,注意有先后順序的,如果找不到,會提示 command not found。
如果是自己編譯安裝的軟件,剛開始要執行的話,前面需要指定路徑(絕對路徑和相當路徑都可以),如果想像系統命令一樣,不管在哪里只需要輸入命令都可以執行的話,需要把 軟件的路徑 添加到環境變量中,如何添加呢?
1、使用export命令: 只在當前的session中有效
export PATH=$PATH:/opt/nginx/sbin
2、在系統已有的路徑中比如:/usr/local/bin 中添加 你的可執行文件的硬鏈接(或軟鏈接)
ln /opt/redis-4.0.10/src/redis-server /usr/local/bin/redis-server
ln /opt/redis-4.0.10/src/redis-cli /usr/local/bin/redis-cli
3、修改 ~/.bashrc 文件 :只對當前用戶有效
vim ~/.bashrc
在里面加一行: export PATH=$PATH:/opt/ruby/bin
讓環境變量立即生效需要執行如下命令:source ~/.bashrc
4、修改/etc/profile文件 :對系統里所有用戶都有效
vim /etc/profile
在里面加一行: export PATH=/opt/python36/bin:$PATH
最后可以直接輸入命令執行或者echo $PATH 來檢驗是否修改配置成功。
Advanced Bash-Scripting Guide 高級腳本編程指導 (有興趣可以好好讀一下)
在Linux Shell Cookbook, Second Edition中還提到一種自定義命令在系統環境變量中添加變量:

However, we can make this easier by adding this function in .bashrc-: prepend() { [ -d "$2" ] && eval $1=\"$2':'\$$1\" && export $1; } This can be used in the following way: prepend PATH /opt/myapp/bin prepend LD_LIBRARY_PATH /opt/myapp/lib How it works... We define a function called prepend(), which first checks if the directory specified by the second parameter to the function exists. If it does, the eval expression sets the variable with the name in the first parameter equal to the second parameter string followed by : (the path separator) and then the original value for the variable. However, there is one caveat, if the variable is empty when we try to prepend, there will be a trailing : at the end. To fix this, we can modify the function to look like this: prepend() { [ -d "$2" ] && eval $1=\"$2\$\{$1:+':'\$$1\}\" && export $1 ;} In this form of the function, we introduce a shell parameter expansion of the form: ${parameter:+expression} This expands to expression if parameter is set and is not null. With this change, we take care to try to append : and the old value if, and only if, the old value existed when trying to prepend.