Unset all ENV variables matching _PROXY

awkenvironment-variablesgrepxargs

I'm trying to unset all environment variables that match _PROXY:

env | grep -i _proxy | column -t -s '=' | awk '{ print $1 }' | grep -iv 'no_proxy' | xargs -0 -I variable unset variable

but it's failing with xargs: unset: No such file or directory.

If I try changing unset to echo, however, everything seems to work as expected: I get a list of variables that are set.

env | grep -i _proxy | column -t -s '=' | awk '{ print $1 }' | grep -iv 'no_proxy' | xargs -0 -I variable echo variable
http_proxy
ftp_proxy
FTP_PROXY
https_proxy
HTTPS_PROXY
HTTP_PROXY

What seems to be going wrong? (If you have an alternate strategy for accomplishing the goal, I'm interested, but I'd most of all like to know why this is failing.)

Also, I'm using OS X, in case that's relevant.

Best Answer

That's because unset is a shell builtin and not an external command. This means that xargs can't use it since that only runs commands that are in your $PATH. You'd get the same problem if you tried with cd:

$ ls -l
total 4
drwxr-xr-x 2 terdon terdon 4096 Jun 16 02:02 foo
$ echo foo | xargs cd
xargs: cd: No such file or directory

One way around this is to use a shell loop which, since it is part of the shell, will be able to run shell builtins. I also simplified your command a bit, there's no need for column, you can set the field separator for awk and there's no need for a second grep, just tell awk to print lines that don't match no_proxy:

while read var; do unset $var; done < <(env | grep -i proxy | 
    awk -F= '!/no_proxy/{print $1}')