How do I redirect a bash variable to an executable?

I have an executable, let's say it's called a.out

. It takes two lines of input after the request -

> ./a.out 
> give me input-1: 0 0 10
> give me input-2: 10 10 5
> this is the output: 20 20 20

      

I can store inputs in a file (input.txt) and redirect to a.out

, the file looks like this:

0 0 10
10 10 5

      

and I can call a.out

like -

> ./a.out < input.txt
> give me input-1: 0 0 10 give me input-2: 10 10 5
> this is the output: 20 20 20

      

Now I want to store multiple entries in this file and redirect to a.out

. The file will look like this: 2 inputs -

0 0 10
10 10 5
0 0 20
10 10 6

      

and i write bash script as -

exec 5< input.txt
while read line1 <&5; do
      read line2 <&5;
      ./a.out < `printf "$line1\n$line2"` ;
done

      

It doesn't work, how to do it?

+3


source to share


1 answer


<

the name of the file containing the content is required, not the content itself. Maybe you just want to use a pipe:

exec 5< input.txt
while read line1 <&5; do
    read line2 <&5
    printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done

      

or process override:

exec 5< input.txt
while read line1 <&5; do
    read line2 <&5
    ./a.out < <(printf "%s\n%s\n" "$line1" "$line2")
done

      

However, you don't need to use a separate file descriptor. Just redirect standard input to a loop:

while read line1; do
    read line2
    printf "%s\n%s\n" "$line1" "$line2" | ./a.out
done < input.txt

      

You can also use the doc here (but note the indentation):



while read line1; do
    read line2
    ./a.out <<EOF
$line1
$line2
EOF
done < input.txt

      

or here the line:

while read line1; do
    read line2
    # ./a.out <<< $'$line1\n$line2\n'
    ./a.out <<<"$line1
$line2"
done < input.txt

      

A newline can be included using a special quote $'...'

, which can indicate \n'

a newline with , or the line can simply have a newline embedded.


If you are using bash

4 or newer, you can use the option -t

to detect the end of the input, so it a.out

can read directly from the file.

# read -t 0 doesn't consume any input; it just exits successfully if there
# is input available.
while read -t 0; do
    ./a.out
done < input.txt

      

+5


source







All Articles