简体   繁体   中英

Bash: how to unset an env variable with a hyphen (-)?

I have in my environment some variables that have an invalid identifier. When I try to unset them, I get the following error:

$ unset A-B
bash: unset: `A-B': not a valid identifier

How to unset them?

Related to the answer by Honza P :

According to man bash the environment variables have the form name=value where name consists only of alphanumeric characters and underscores, and begins with an alphabetic character or an underscore. So the name AB is an invalid variable identifier for Bash, and cannot be used or accessed because it has internal validations (enforced strongly in late Bash versions because of vulnerabilities in Bash itself). The only solution is starting another secondary sub-shell that not have the offending names using the utility env to erasing them before launching Bash:

env -u 'A-B' bash

Note that the single quotes aren't needed, but to me is more readable that way as indicates the text inside is a string, not other command.

If you have more variables simply list them separated by spaces, or if you want to run only an script without the variables you can use for example:

env -u 'A-B' 'OTHER-VAR' 'bad-name' bash -c 'myscript.sh arg1 arg2'

The subshell will run myscript.sh with the arguments arg1 and arg2 , and exit to the current Bash shell.

Consult the man page of 'env': man env

Not the best solution I guess but it worked in my case.

I tried an example by bishop env -u "foo-bar=baz" , then env -u "foo-bar" but this approach still left some garbage in variables eg _=foo-bar . So I used unset _ and then it is gone.

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