0

I have an situation where there are some number ~ 10 - 30 of environmental variables which pertain to a specific application. Before re-configuring and re-compiling the application I want to remove (i.e. unset) all relevant env vars. 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.

Community
  • 1
  • 1
villaa
  • 1,043
  • 3
  • 14
  • 32

3 Answers3

1

This seems to work:

unset `printenv |grep G4 |awk 'BEGIN{FS="=";}{printf("%s ",$1);}'`

And I guess it's related to the answer for: Unset group of variables

I just didn't realize it

Community
  • 1
  • 1
villaa
  • 1,043
  • 3
  • 14
  • 32
  • No, the link you posted is not related at all: it's for php whereas the question is for the shell – Eric Apr 07 '19 at 11:54
1

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.

Peter Westlake
  • 4,894
  • 1
  • 26
  • 35
-1
declare -a vars_to_unset=(blue green red)
unset ${vars_to_unset[@]}

Will unset $blue, $green and $red at once.

Extending to the variables containing G4:

declare -a arr=($(env | cut -d= -f1 | grep G4))
unset ${arr[@]}
Eric
  • 1,138
  • 11
  • 24