如何在 shell 脚本中将 unset 与 xargs 一起使用?

sor*_*abz 2 bash shell xargs

我想写bash脚本,删除一些环境变量

我的问题是当我运行以下命令时

env | grep -i _proxy= | cut -d "=" -f1 | xargs -I {} echo {}
Run Code Online (Sandbox Code Playgroud)

我看到下面的结果

HTTPS_PROXY
HTTP_PROXY
ALL_PROXY
Run Code Online (Sandbox Code Playgroud)

但是当我替换echo为 时unset,如下所示

HTTPS_PROXY
HTTP_PROXY
ALL_PROXY
Run Code Online (Sandbox Code Playgroud)

我看到下面的错误

xargs: unset: No such file or directory
Run Code Online (Sandbox Code Playgroud)

我的问题是什么?如果我使用xargs不当?

gle*_*man 5

您有 xargs 在管道中运行。因此,它在单独的进程中运行,并且无法更改“父”shell 的环境。

此外,xargs 与命令一起使用,而不是 shell 内置命令。

你需要这样做:

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

或者

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