简体   繁体   中英

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? 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 . 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. (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.

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.

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. Otherwise, modify the regexp for the conditional.

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. But I repeat... THIS IS A VERY BAD PRACTICE, BE CAREFUL!!

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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