简体   繁体   English

努力取消设置 bash 中的环境变量

[英]Struggling to unset an environment variable in bash

I have previously set an environment variable using:我之前使用以下方法设置了一个环境变量:

echo export "AVARIABLE=example" >> ~/.bash_profile

but now after using:但现在使用后:

unset AVARIABLE

the env var remains when I open a new shell?当我打开一个新的 shell 时,环境变量仍然存在吗? What am I doing wrong here?我在这里做错了什么? Even running:甚至跑步:

source ~/.bash_profile

does not work?不起作用?

If you are opening a new shell, about the first thing it does is to source ~/.bash_profile . 如果要打开新的外壳,则要做的第一件事就是获取~/.bash_profile And there, the variable is set again. 然后,再次设置变量。

If you want to get rid of it permanently, edit your ~/.bash_profile to remove the line in question again. 如果要永久删除它,请编辑~/.bash_profile以再次删除有问题的行。 (This will only take effect for new sessions.) (这仅对新会话有效。)

If you only want to unset it in your current shell, then unset is fine but as you've seen, it won't affect new invocations of the shell. 如果只想在当前shell中unset ,那么unset很好,但是如您所见,它不会影响shell的新调用。

Do this: 做这个:

#!/bin/bash

file="~/.bash_profile"

readarray -t FILE < <(cat < "${file}")
rm -rf "${file}"
for item in "${FILE[@]}"; do
    if [[ ! "${item}" =~ export ]]; then
        echo "${item}" >> "${file}"
    fi
done

Beware!! 谨防!! this is going to save in an array the content of your .bash_profile file... then will DELETE it and then will try to generate it again with all the same lines excepting the line that matches the regular expresion you need... I put only "export" but check this because this could remove other lines depending of the content of your .bash_profile. 这将把.bash_profile文件的内容保存在数组中...然后将其删除,然后将尝试使用所有相同的行再次生成它,除了与需要的常规表达式相匹配的行...我放仅“导出”,但请检查此内容,因为这可能会删除其他行,具体取决于您的.bash_profile的内容。

So beware with this... If you are pretty sure that there is only a line on your .bash_profile containing the string "export" and that line is what you want to remove, this is your script. 因此要当心……如​​果您非常确定.bash_profile上只有一行包含字符串“ export”,并且该行就是您要删除的行,那么这就是您的脚本。 Otherwise, modify the regexp for the conditional. 否则,修改条件的regexp。

And be careful with the permissions and the owner of the file after this. 之后请注意文件的权限和所有者。 Usually they are 644 and if you launch it with the same user owning the home dir, you'll have no problems. 通常它们是644,如果您与拥有home目录的同一用户启动它,则不会有任何问题。 But I repeat... THIS IS A VERY BAD PRACTICE, BE CAREFUL!! 但是我重复一遍……这是非常糟糕的做法,请谨慎!

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM