'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?
Solution 1:[1]
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 A-B
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
Solution 2:[2]
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 e.g. _=foo-bar
. So I used unset _
and then it is gone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Honza P. |