Bash: run command on file change and on standard input

I have a nice file watcher using fswatch:

cmd="go install ./..."
$cmd
fswatch -0 ./ | while read -d "" event; do
  echo "File Changed: $event"
  $cmd
done

Now I also want to listen for input at the command-line, so if I type in anything, $cmd will be run

I don't want to stop and start fswatch a lot (like in a loop) because it might miss a change.

What is the best way to do this?

Answers

The easiest way is to put your while-loop in the background and start a second while-loop for the commandline:

cmd="go install ./..."
$cmd
fswatch -0 ./ | while read -d "" event; do
    echo "File Changed: $event"
    $cmd
done &
while read -r line ; do
    echo "Commandline: $line"
    $cmd
done

There is also a way to use a fifo:

mkfifo nicename
cmd="go install ./..."
$cmd
tail -f nicename | while read -d "" event; do
    echo "File Changed: $event"
    $cmd
done &

fswatch -0 ./ >> nicename &
cat >> nicename

The fifo allows you to use even more that two input-processes to use your loop.

Posted on by Ljm Dullaart