I have an situation where there are some number, approximately 10 - 30, of environmental variables which pertain to a specific application. Before reconfiguring and recompiling the application, I want to remove (i.e., unset) all relevant environment variables. The list is too annoying to type out explicitly, so I'd like some automation.
I've looked at Unset group of variables, but it seems to be not quite what I want.
I came up with the below command, which shows what I want to do in principle (unset all environmental variables with "G4" in the names—actually it's not quite perfect it will unset it if it has "G4" in the values too).
printenv |grep G4 |awk 'BEGIN{FS="=";}{system("unset "$1);}'
As I should have expected, this doesn't affect the parent shell, which is the behaviour I want. I have encountered this before, in those cases I've used 'source', but I can't quite see how to do that here. It does not work to put the above command in a shell script and then source that, it seems.
I know I can just find out what's setting those variables in the first place and remove it and open another shell but I don't consider that a solution (although it's probably what I'll do while this question is being answered). I also don't want to unset them one-by-one, that's annoying and it seems like that shouldn't be necessary.
That's nearly right. What you need to do is to get those commands out into the parent shell, and the way to do that is with command substitution. First print out the names of the variables. Your awk
command is one way to do that:
printenv |grep G4 |awk 'BEGIN{FS="=";}{print $1;}'
Then use command substitution to feed the output to the shell:
unset $(printenv |grep G4 |awk 'BEGIN{FS="=";}{print $1;}')
The $(...)
gives the output of the command to the shell, exactly as if you had typed it. I say "almost" because the shell processes the output a little, for instance removing newlines. In this case that's fine, because the unset
command can take the name of multiple variables to unset. In cases where it would be a problem, quote the output using double quotes: "$(....)"
. The link gives all the details.