[nycbug-talk] nifty(1)

Isaac Levy ike at blackskyresearch.net
Wed Dec 14 18:13:11 EST 2011


On Dec 14, 2011, at 5:28 PM, Matthew Story wrote:
> who's up next?
This nifty(1) thread is a great idea!

"The 3-finger Claw Technique"  The sweetest 3 functions, ever.

  shout() { echo "$0: $*" >&2; }
  barf() { shout "$*"; exit 111; }
  safe() { "$@" || barf "cannot $*"; }

I use these daily, they're extremely cross-platform friendly in any bourne-derived shell I've  used in the last 3 years.


safexample.sh :
--
#!/bin/sh

shout() { echo "$0: $*" >&2; }
barf() { shout "$*"; exit 111; }
safe() { "$@" || barf "cannot $*"; }

# consider the following lines
safe cd /some/dir
safe tar xzvfp /my/big/tarball.tbz

exit 0
--


In the above example, using 'safe' suddenly gives the user the following special powers:

1) if '/some/dir' does not exist, the script will safely exit before that un-tarring does any damage.

2) the actual 'directory does not exist' will return to stderr for the script, (as opposed to just telling us the useless fact that the enclosing script failed).
Now bourne shell starts behaving like a modern language!  (ala Python/Ruby tracebacks, Perl errors, etc…)

Additonally, if you 'exit 0' at the end, you can run non-safe operations, and always be guaranteed that if the shell exits, it was 'complete'.
An example:

# consider the following lines
safe cd /some/dir
tar xzvfp /my/big/tarball.tbz

Now, safe was removed from the un-tar command, right?  So, imaging tarballs created by people using a Mac (with HFS+ and some filesystem-specific sticky bit somewhere in the filesystem which was tar'd up).
Now, you un-tar it on some *BSD or other *NIX box, and tar complains as it goes- and exits non-zero.  One way to handle this, is to consider the tar 'reliable', and not use safe for it.

Now, if we continue to be conscious of this simple safe/notsafe distinction with these scripts, they can be called by other safe scripts- and behave just like any respectable UNIX program!

Now, consider this crontab entry:
1	3	*	*	*	someuser flock -k /tmp/safexample.lock /path/to/safexample.sh

If it fails, (for bad perms, no tarball to unpack, etc…)  cron will actually have a reasonable message to email/log on failure!


Thanks to the noble efforts of the Clan of the White Lotus, these 3 functions originate during the late thirteenth century, around Guangzhou.  It is rumored these 3 functions took 15 years to boil down- I beileve that after mercilessly abusing them for the last 3 years myself…  (I'm not kididng about that part!)

Attached, is another example with more bits.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: nonsense.sh
Type: application/octet-stream
Size: 338 bytes
Desc: not available
URL: <http://lists.nycbug.org/pipermail/talk/attachments/20111214/75e8010b/attachment.obj>


More information about the talk mailing list