Yair B. Yair B. - 26 days ago 5
Linux Question

Redirecting output of a shell script to a program

I have a file named

numbers.txt
. In the file I have all the numbers from 1 to 1000. And I have a program that inserts 1 to 5 in 200 round.

I tried the following script:

while read p; do
echo $((p % 5 + 1))
done <numbers.txt


It prints numbers from 1 to 5 in 200, as expected.

Now I need to redirect the output to the input of my program. I tried this:

./my-program < while read p; do
echo $((p % 5 + 1))
done <numbers.txt


But it failed an error:


syntax error near unexpected token `do'


How can I run
./my-program
with input from the loop?

Answer

./my-program < ... - this syntax is only for files, in your case you want to use this type of redirection:

while read p; do
  echo $((p % 5 + 1))
done <numbers.txt | ./my-program