muffel
muffel

Reputation: 7390

Executing a command if a program outputs a special string in shell script

I have am using a backup script that uses rsync to create a backup of my data, encrypts it and uploads it to the cloud. The script runs in an isolated docker container which only has access to the data it should backup (it cannot communicate with the host).

As the services whose data is backed up may not be running while backing up, I am currently executing the backup task (simplified) like this

#!/bin/bash
/etc/init.d/myservice stop
# the scripts blocks until the backup job is done
/opt/backup_data >> /var/log/backup.log
/etc/init.d/myservice start

and the output of the backup service looks like

backup started at 15-02-09 22:00:01
rsync started
/foo/bar
deleted /baz
[...]
rsync completed
starting upload
upload completed
backup completed 

While this works, I would prefer to restart my services as soon as the rsync operation is finished, to keep the downtime as small as possible. But as all I have is the content of the log, how can I realized this?

TL;DR I run a command that outputs some text to stdout, which I redirect to file. I want to enforce that another command is executed as soon as the stdout of the first one contains a special string. If it doesn't (e.g. while something went wrong), I want to execute it anyway - but only once.

Upvotes: 0

Views: 66

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 208107

As the docker container's host can see the log file, I would use tail -f to "follow" the log file and pipe its output into awk. When awk "sees" that the rsync job is complete, it can restart the services:

tail -f backup.log | awk '/^rsync complete/ {system("/etc/init.d/myservice start")}'

Upvotes: 1

Related Questions