CentOS设置系统环境变量

1)第一次尝试的天真做法:

以注册golang环境变量为例:

cd /etc/profile.d
ls -rtl
touch custom.sh # or any file name you like to create a new file
ls -rtl
echo "export PATH=\${PATH}:/usr/local/go/bin" > custom.sh && chmod 755 custom.sh
less custom.sh
. custom.sh
echo $PATH
reboot


不建议直接写入/etc/profile,而是在/etc/profile.d文件夹下新建一个自己写的shell脚本,内容是:

export PATH=${PATH}:/usr/local/go/bin

系统启动会自动执行这一脚本


详情见/etc/profile文本的内容:

# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

pathmunge () {
    case ":${PATH}:" in
        *:"$1":*)
            ;;
        *)
            if [ "$2" = "after" ] ; then
                PATH=$PATH:$1
            else
                PATH=$1:$PATH
            fi
    esac
}

...

for i in /etc/profile.d/*.sh ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then 
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done


$- 代表当前shell的选项,See 1  2  3

echo "$-" 显示的是 himBH (5个选项)

${-#*i} 中的*这里是字符串通配符,#这里是字符串操作符,${string#match_string}

Deletes shortest match of $match_string from front of $string. See 4

所以${-#*i} 是 mBH


但是,上述做法之后,在Terminal中echo $PATH中会出现两次/usr/local/go/bin。虽然无伤大雅,但也挺奇怪的,难道这个脚本被执行了两次?

是的,被执行了两次:

~/.bashrc  ->  /etc/bashrc 中也执行了一遍。


2)恰当的做法:

利用/etc/profile (/etc/bashrc)中定义的pathmunge 函数去除重复:

echo "pathmunge /usr/local/go/bin after" > custom.sh && chmod 755 custom.sh

5

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值