使用xargs将stdin分配给变量 [英] Using xargs to assign stdin to a variable

查看:268
本文介绍了使用xargs将stdin分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真正想做的就是确保管道中的所有内容都成功完成,并将最后一个stdin分配给一个变量.考虑以下愚蠢的情况:

All that I really want to do is make sure everything in a pipeline succeeded and assign the last stdin to a variable. Consider the following dumbed down scenario:

x=`exit 1|cat`

当我运行declare -a时,我看到了:

When I run declare -a, I see this:

declare -a PIPESTATUS='([0]="0")'

我需要某种方式来注意到exit 1,所以我将其转换为:

I need some way to notice the exit 1, so I converted it to this:

exit 1|cat|xargs -I {} x={}

declare -a给了我

declare -a PIPESTATUS='([0]="1" [1]="0" [2]="0")'

这就是我想要的,所以我尝试看看如果exit 1没有发生会发生什么:

That is what I wanted, so I tried to see what would happen if the exit 1 didn't happen:

echo 1|cat|xargs -I {} x={}

但是它失败了:

xargs: x={}: No such file or directory

有什么办法让xargs将{}分配给x?使用PIPESTATUS工作并将stdin分配给变量的其他方法怎么样?

Is there any way to have xargs assign {} to x? What about other methods of having PIPESTATUS work and assigning the stdin to a variable?

注意:这些例子简明扼要.我并不是真正在做exit 1echo 1cat,而是使用这些命令来简化操作,以便我们专注于我的特定问题.

Note: these examples are dumbed down. I'm not really doing an exit 1, echo 1 or a cat, but used these commands to simplify so we can focus on my particular issue.

推荐答案

xargs在子进程中运行,您调用的所有命令也一样.因此它们不会影响您的Shell的环境.

xargs is run in a child process, as are all the commands you call. So they can't effect the environment of your shell.

您也许可以使用命名管道(mkfifo)或bash的read函数执行某些操作?

You might be able to do something with named pipes (mkfifo), or possible bash's read function?

也许只是将输出重定向到文件,然后可以使用PIPESTATUS:

Maybe just redirect the output to a file, then you can use PIPESTATUS:

command1 | command2 | command3 >/tmp/tmpfile
## Examine PIPESTATUS
X=$(cat /tmp/tmpfile)

这篇关于使用xargs将stdin分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆