run a command whenever a file is touched

ontouchdo(){ while :; do a=$(stat -c%Y "$1"); [ "$b" != "$a" ] && b="$a" && sh -c "$2"; sleep 1; done }
This is useful if you'd like to see the output of a script while you edit it. Each time you save the file the command is executed. I thought for sure something like this already exists - and it probably does. I'm on an older system and tend to be missing some useful things. Examples: ontouchdo yourscript 'clear; yourscript somefiletoparse' Edit yourscript in a separate window and see new results each time you save. ontouchdo crufty.html 'clear; xmllint --noout crufty.html 2>&1 | head' Keep editing krufty.html until the xmllint window is empty. Note: Mac/bsd users should use stat -f%m. If you don't have stat, you can use perl -e '$f=shift; @s=stat($f); print "$s[9]\n";' $1

10
2010-10-22 23:25:12

5 Alternatives + Submit Alt

What Others Think

Nice! Was this inspired by the ever useful onlogdo script? http://www.sigterm.net/projects/onlogdo
hackerb9 · 400 weeks and 2 days ago
Nice! Added to my personal collection of usefull oneliners. I also added 2> /dev/null after the stat command, so I can do; ontouchdo nonexistingfile 'date', to see when that file gets created..
xeor · 400 weeks and 2 days ago
@hackerb9 I'm not familiar with onlogdo, but I did have the funny feeling I was reinventing the wheel. ;) I'll check it out. @xeor Good idea! I'll try it on my copy.
putnamhill · 400 weeks and 1 day ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: