Linux environment variables (环境变量)

Posted Battlefield

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux environment variables (环境变量)相关的知识,希望对你有一定的参考价值。

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 命令来查看:

[[email protected] ~]# 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 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.
View Code

以上是关于Linux environment variables (环境变量)的主要内容,如果未能解决你的问题,请参考以下文章

安装oracle 出现Environment variable: "PATH" -

报错记录Linux shell脚本报TERM environment variable not set.

如何解决mips-openwrt-linux-gcc: environment variable "STAGING_DIR" not defined?

Linux下tomcat启动Neither the JAVA_HOME nor the JRE_HOME environment variable is defined At least one of

解决Linux下启动Tomcat遇到Neither the JAVA_HOME nor the JRE_HOME environment variable is defined

linux tomcat 启动报错 Neither the JAVA_HOME nor the JRE_HOME environment variable is defined At least on