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 来检验是否修改配置成功。
在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 usedinthe following way:
prepend PATH/opt/myapp/bin
prepend LD_LIBRARY_PATH/opt/myapp/lib
How it works...
We define afunction called prepend(), which first checks ifthe directory specified by the
second parameter to thefunction exists. Ifit does, the eval expression sets the variable with
the nameinthe first parameter equal to the second parameter string followed by : (the path
separator) and then the original valueforthe variable.
However, there is one caveat,ifthe variable is empty when we try to prepend, there will be a
trailing : at theend. To fix this, we can modify the functionto 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 expressionifparameter is set and is not null.
With this change, we take care to try to append : and the old valueif, and only if, the old
value existed when trying to prepend.
View Code