Tenebris Tenebris - 6 months ago 15
Linux Question

Input through pipe in separate terminal

Hi I am trying to build a program in bash. The idea is that I would have open two terminals. One would take the input with a pipe

cat > pipe
. The other terminal would be running a bash script with a while true loop and read the input from the pipe. The input would be stored to a variable and further action would occur depending on what is stored inside. This is what I tried.

The program gets the pipe name as an argument and it is stored to the variable pipe.

while true; do
input=$(cat<$pipe)
if [ "$input" == "exit" ]; then
exit 0
fi
done


I have tried to input an exit string throught the pipe but the program does not stop as it should. If the variable does not get any value from the pipe how would I correct that? Or is something else wrong that prevents the exit from happening?

Answer

Your second script should be something like :

#!/bin/bash
pipe="$1" # Here $1 is full path to the file pipe as you have confirmed
while true
  do
input=$(cat<"$pipe")
if [[ $input =~ exit ]] #original line was if [ "$input" == "exit" ]
  then
exit 0
fi
done

Remember $(cat<"$pipe") will store the entire file as a string. So, even though you have the word exit somewhere down in the pipe file the original condition if [ "$input" == "exit" ] will be false except the case when the first word you enter for cat>pipe itself is "exit".

A little tweakish solution is do a regex match (=~) as I have done but this solution is not very reliable because if you enter something like "I don't wanna exit", for cat>pipe the second script will exit.

A second solution would be :

#!/bin/bash
pipe="$1"
while true; do
input=$(tail -n1 "$pipe") #checking only the last line
if [[ "$input" == "exit" ]] #original if condition
  then
exit 0
fi
done