Search code examples
shellshcatfifomkfifo

rewrite shell script so that cat does not evade the check


Currently, I use

#!/bin/sh
while [ -e "${XDG_RUNTIME_DIR}" ]; do cat ${FIFO} ; done | my_program

to create a fifo for my_program, which reads from stdin.

The problem is that cat breaks out of the while loop check, and the process continues after my xdg_runtime_dir does not exist anymore.

Is there a way to rewrite this, so that the check is enforced, i.e. when xdg_runtime_dir does not exist, the process terminates?


Solution

  • The while construct can test for two commands if you chain them with &&:

    while test -e "${XDG_RUNTIME_DIR}" && cat ${FIFO}; do
        sleep 1
    done | my_program
    

    Now if either condition is false, the loop terminates.

    Note that if you want to terminate only on the second condition, you could use

    while okToFail -xy; cat ${FIFO}; do ...
    

    since while actually takes a list of commands, and the exit status of a list is the status of the last command.