[colug-432] Gracefully Doing Nothing

Rick Hornsby richardjhornsby at gmail.com
Mon Jan 30 13:37:07 EST 2017


On January 30, 2017 at 11:57:53, jep200404 at columbus.rr.com (
jep200404 at columbus.rr.com) wrote:

How does one do nothing gracefully in a Bourne shell for loop?

A example that fails to do nothing gracefully follows.


Typically, I'd think of two approaches to this. The first is just to throw
away any error output. That's probably not ideal, because in case something
goes wrong (destination volume full, etc) you won't know.

The other is to generate an array of files, then wrap your loop in an if
statement. "if" might not seem super cool, but it might do the trick for
you:

$ cat backup.sh
prefix=<set the date or whatever>
files=([a-z]*)
if [ -e "${files[0]}" ]; then
    for f in "${files[@]}"; do
        mv "$f" "$prefix-$f"
    done
fi

The advantage this if/loop has over a more compact or perhaps "elegant"
approach is that it tries to be readable.

An option that might be slightly less readable but could be done in fewer
lines (eliminates the explicit loop construct entirely) is to use `find`
with exec mv or xargs. I haven't tested this, so consider it metacode -

find . -name '^[a-z]*' -maxdepth 1 -exec mv "{}" "$prefix-{}" \;

* I tested this find command and it is wrong (needs revising), but it's the
idea that counts, right? ;)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.colug.net/pipermail/colug-432/attachments/20170130/f5625cff/attachment.html 


More information about the colug-432 mailing list