1

I have written two scripts. One is myscipt1.sh which reads a sequence of integer numbers (provided as arguments) and reports a final number:

[user@pc user] ./myscript1.sh 34 45 67 234
[user@pc user] 1200

In the above example, the script returns 1200. Another script myscript2.sh takes a string as input and returns a sequence of integer numbers:

[user@pc user] ./myscript2.sh a string to provide
[user@pc user] 364 465 786 34 22 1

I want to call myscript1.sh by passing the result of myscript2.sh, so I tried:

[user@pc user] ./myscript2.sh my_string | ./myscript1.sh

But I have no luck as myscript1.sh (wich performs a check on the number of arguments passed, exiting of no arguments are passed) reports that no arguments were passed.

Looks like Bash have problems when I use pipes with scripts I write. How to do?

4

4 回答 4

3

您可以将其运行为:

./myscript1.sh $(./myscript2.sh my_string)
于 2013-11-06T10:41:08.247 回答
2

利用xargs

[user@pc user] ./myscript2.sh my_string | xargs ./myscript1.sh
于 2013-11-06T10:39:24.127 回答
2

管道不是那样工作的。

管道从程序/脚本获取输出并将其作为标准输入发送到另一个程序/脚本,而不是作为命令行参数。例如,您可以使用readline从第一个程序通过管道读取数据。

你应该使用xargs(正如 Joucks 在我写作时所说的那样:))来做到这一点。

于 2013-11-06T10:42:55.453 回答
1

如果您使用管道,请重写您的脚本,以便他们期望输入不是作为参数,而是从标准输入中读取:

input=$1  # old version

read input  # new version

然后你可以像以前一样使用管道。

于 2013-11-06T10:46:39.960 回答