UNIX Pipes – event triggers action

[problem]

You want to listen on a pipe and perform commands, based on the text sent to the pipe.

This could be useful for triggering action based on events;
Running code as different users – i.e. allow root or a functional user to run something – just need to allow access to group of users, via permission to write to the pipe.

[/problem]

[solution]


1. mknod /tmp/.restart_crd

2. chmod a+w /tmp/.restart_crd

3. nohup tail -f /tmp/.restart_crd| while read line
do
case "$line" in
'restart') cmd="./stop >> /tmp/restart.log 2>&1; sleep 5; ./start >> /tmp/restart.log 2>&1";;
'stop') cmd="./stop >> /tmp/restart.log 2>&1";;
'start') cmd="./start >> /tmp/restart.log 2>&1";;
*) cmd="no match ${line}.";;
esac

echo "command is $cmd"
eval $cmd

sleep 5

done &

4. disown

[/solution]

[example]


$ echo "restart" > /tmp/.restart_crd

$ echo "start" > /tmp/.restart_crd

$ echo "stop" > /tmp/.restart_crd

Watch output in by tail -f /tmp/restart.log

[/example]

[reference]

[tags], Unix Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *