reading in from stdin from a command executed with xargs

久未见 提交于 2019-12-30 18:00:11

问题


Using xargs did something I didn't quite expect, though I guess it sort of makes sense. This is not what I did, but this is an example which should show what happened.

fn.sh

#!/usr/bin/bash
index=1
for arg in "$@"; do echo "Arg #$index = '$arg'"; let ++index; done
read -p "type something followed by enter: "  a
echo "You typed '$a'."

Now here is the command:

echo boo hoo | xargs ./fn.sh

Now what I want is that fn.sh can read from stdin to allow user interaction, but that's been usurped by xargs. I guess I could get xargs to read from a temporary file, but I was wondering if it can use an unnamed file.


回答1:


I've never used cygwin, but normally I'd do something like this:

xargs -a <(echo boo hoo) ./fn.sh

-a tells xargs to read from a file, and the <( ) syntax (which might or might not work with cygwin) is process substitution, which effectively creates a named object (either a named pipe or a path starting /dev/fd) which can be read, yielding the result of running the enclosed command.

That's not as convenient as pipe syntax, since you have to put the data source in the middle of the xargs command, but it's otherwise equivalent.




回答2:


I found this question trying to solve the same issue, and then took a closer look at the xargs manpage.

The -o option should accomplish exactly and predictably what is desired:

-o: Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application.

Just wanted to update the answer to this older question as it was the first result in my search.



来源:https://stackoverflow.com/questions/19961319/reading-in-from-stdin-from-a-command-executed-with-xargs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!