1

I am experimenting with named pipes in Ubuntu and have no prior experience with them. I did the following:

mkfifo pipe
ls>pipe&
cat pipe

This enters a list of all files in my folder into pipe and displays them. I am trying to read the pipe 2 lines at a time. So, I want a command when executed once, will give the names of first and second files in the folder. If the command is executed again, I want third and fourth filenames. Is there any way to do it?

I tried head -2 pipe. It displayed first two filenames. But when it was executed again, it hanged. What would be the right direction to proceed?

  • 1
    You may want to read line by line with the shell built-in read. – AlexP Oct 22 '19 at 21:37
3

You want to keep the fifo open on the reading side. One way is to let bash keep an open file descriptor to it.

 #!/bin/bash
 mkfifo pipe
 ls > pipe &
 exec 8< pipe
 r2(){
   read -ru 8 fn1
   read -ru 8 fn2
   echo "$fn1" "$fn2"
 }
 r2 # print out first 2 files
 sleep 1 # do something
 r2 # print out next 2 files.
  • Thank you so much. That works. – skr_robo Oct 23 '19 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.