linux的环境变量注册表,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 命令来查看:

[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中还提到一种自定义命令在系统环境变量中添加变量:

a5910c9db74e3822848e10fba2e2bfd39ff.jpg

8c598ed6c21b1782d27164aa0a2df7a64aa.jpg

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值