How to use unset with xargs in shell script?

Viewed 356

ITNOA

I want to write bash script, to remove some environmental variable

my problem is when I run below command

env | grep -i _proxy= | cut -d "=" -f1 | xargs -I {} echo {}

I see below result

HTTPS_PROXY
HTTP_PROXY
ALL_PROXY

but when I replace echo with unset, something like below

env | grep -i _proxy= | cut -d "=" -f1 | xargs -I {} unset {}

I see below error

xargs: unset: No such file or directory

What is my problem? If I use xargs incorrectly?

2 Answers

You have xargs running in a pipeline. Therefore it is running in a separate process, and it cannot alter the environment of the "parent" shell.

Also, xargs works with commands, not shell builtins.

You'll need to do this:

while read -r varname; do unset "$varname"; done < <(
    env | grep -i _proxy= | cut -d "=" -f1
)

or

mapfile -t varnames  < <(env | grep -i _proxy= | cut -d "=" -f1)
unset "${varnames[@]}"

I came across this:

]$ env |grep AWS_|tr "=" " "|awk '{print $1}'
AWS_SESSION_TOKEN
AWS_SECRET_ACCESS_KEY
AWS_ACCESS_KEY_ID
]$ env |grep AWS_|tr "=" " "|awk '{print $1}'|xargs -n1 unset
xargs: unset: No such file or directory
]$ 

And below simple solution worked for me

unset `env |grep AWS_|tr "=" " "|awk '{print $1}'`

or below

unset `env |grep AWS_|cut -d= -f1`
Related