码迷,mamicode.com
首页 > 系统相关 > 详细

Linux environment variables (环境变量)

时间:2019-04-14 12:46:46      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:添加   顺序   var   shel   linu   can   变量   not found   close   

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 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 (环境变量)

标签:添加   顺序   var   shel   linu   can   变量   not found   close   

原文地址:https://www.cnblogs.com/51try-again/p/10704576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!