Home > other >  How to use unset with xargs in shell script?
How to use unset with xargs in shell script?

Time:10-23

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?

CodePudding user response:

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[@]}"
  • Related