rewrite shell script so that cat does not evade the check

45 views Asked by At

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?

1

There are 1 answers

2
Jens On BEST ANSWER

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.