I'm having quite some trouble with two bash-scripts I am working on:
script.sh
#!/bin/bash
while true; do
read -p "script: read: var: " var
echo "script: write: var: $var"
done
pipe.sh
#!/bin/bash
while read line; do
echo "pipe: read: line: (( $line ))"
read -p "pipe: read var: " var < /dev/tty
echo "pipe: write: var: $var"
done< <(cat)
When executing script.sh and piping the output into pipe.sh i get following output:
$ ./script.sh | ./pipe.sh
1: script: read: var: 123 # user entering '123'
2: script: read: var: pipe: read: line: (( script: write: var: 123 ))
3: pipe: read var: 321 # user entering '321'
4: script: read: var: 456 # user entering '456'
5: pipe: write: var: 456
6: pipe: read: line: (( script: write: var: 321 ))
7: pipe: read var:
As you can see everything seems to work until getting to line 4. I was expecting line 4 to be pipe: write: var: 321 from pipe.sh. Instead I get the prompt from script.sh.
Upon entering the string "456" the previously expected line is executed, but with the wrong string (expected: "321", got "456"). In addition line 6 does not print "456" but "321" instead.
Something is totally wrong here. Any suggestions on how to fix this and why this is happening?
Update:
Essentially i would like the pipe to work the same way as the code below.
script1.sh
#!/bin/bash
while true; do
read -p "val1: " val1
script2.sh "${val1}"
done
script2.sh
#!/bin/bash
val1="${1}"
read -p "val2: " val2
echo "${val1} ${val2}"
However, i do not want to hard-code script2.sh into script1.sh. I could pass script2.sh as argument to script1.sh but i initially thought a pipe would be a better solution?
read -pcalls in bothscript.shandpipe.shread from the current terminal, and since the commands in a pipeline run in parallel, you can make no assumptions about which of them is first to snatch the data entered by the user. Theread -pfrom onescript.shmay put out its prompt, but the string entered by the user may be read by theread -pfrompipe.shand vice-versa. I suggest that you re-think your approach../script.sh pipe.shinstead?./script.sh pipe.shwith the those scripts will not runpipe.shat all ;-)script.shis executed and prints the first line (e.g.test1) it should be piped topipe.sh.pipe.shshould processtest1and wait for the next line. whenpipe.shhas processedtest1the next line (e.g.test2) should be piped topipe.shand so on.