2

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?

Andry
  • 16,172
  • 27
  • 138
  • 246
  • 1
    However some commands like `echo` and `ls` can be used in pipes... I do not understand why... – Andry Nov 06 '13 at 10:42
  • 3
    `echo` and `ls` can write to standard output, and therefore appear on the *left* side of a pipe. They can appear on the right side of a pipe, but since they do not read from standard input, they ignore whatever they receive from the pipe, much like `myscript1.sh` seems to be doing. – chepner Nov 06 '13 at 13:38

4 Answers4

5

You can run it as:

./myscript1.sh $(./myscript2.sh my_string)
anubhava
  • 761,203
  • 64
  • 569
  • 643
3

Use xargs

[user@pc user] ./myscript2.sh my_string | xargs ./myscript1.sh
Joucks
  • 1,302
  • 1
  • 17
  • 29
3

Pipes do not work that way.

A pipe gets the output from a program/script and sends it as standard input to another program/script, not as command-line arguments. For example, you can use readline to read the data piped from the first program.

You should use xargs (as Joucks said while I was writing :) ) to do that.

rand
  • 698
  • 5
  • 13
2

If you want to use pipes, then rewrite your script(s) so that they expect their input not as arguments but read it from stdin:

input=$1  # old version

read input  # new version

Then you can use pipes the way you did.

Alfe
  • 56,346
  • 20
  • 107
  • 159