Tuesday, June 4, 2019

bash - Repeat terminal command until specified output



I would like to define an alias that performs a command every x seconds until an underlying process gives a designated output. Then, the command should stop being run.



Is this possible, and if so, how?
Help is much appreciated.



I'm almost satisfied with




alias test1='while true; do ; sleep 1; done'


except I have to manually stop it, and can therefore not make it execute a new command once finished.



The reason for the question:
Dropbox synchronizes poorly at work. Sometimes, I have to restart it. I would like to do that using a command which also tells when the sync is done, e.g. by



alias drop='dropbox stop && dropbox start && while true; do dropbox status; sleep 1; done'



I would like the repetition stopped when Dropbox outputs 'Up to date'.



Set a condition for the while loop



If you replace



while true



by:



while [ "$(dropbox status)" != "Up to date" ]


it works as you describe.



The command



To stop/start Dropbox and finish after synchronizing is done becomes then:




dropbox stop && dropbox start && while  [ "$(dropbox status)" != "Up to date" ]; do dropbox status; sleep 1; done


Or better (to prevent doubling dropbox status):



dropbox stop && dropbox start && while  [ "$(dropbox status)" != "Up to date" ]; do echo "Updating"; sleep 1 ; done && echo "Finished"


Explanation




while true is waiting for a break condition inside the loop (which never comes), but while [ "$(dropbox status)" != "Up to date" makes the loop break if dropbox status returns Up to date


No comments:

Post a Comment

11.10 - Can't boot from USB after installing Ubuntu

I bought a Samsung series 5 notebook and a very strange thing happened: I installed Ubuntu 11.10 from a usb pen drive but when I restarted (...