[colug-432] Gracefully Doing Nothing

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Mon Jan 30 12:56:16 EST 2017


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

A example that fails to do nothing gracefully follows.

    jep at colug:~ $ cat ~/bin/backup 
    #!/bin/sh

    dir=~/stuff
    prefix=`date --iso=ns`

    cd "$dir"
    for f in [a-z]*; do
        mv "$f" "$prefix"-"$f"
    done
    jep at colug:~ $ mkdir stuff
    jep at colug:~ $ cd stuff/
    jep at colug:~/stuff $ ll ~ >foo 
    jep at colug:~/stuff $ ll 
    total 4
    -rw-r--r-- 1 pi pi 1439 Jan 30 12:43 foo
    jep at colug:~/stuff $ backup 
    jep at colug:~/stuff $ ll 
    total 4
    -rw-r--r-- 1 pi pi 1439 Jan 30 12:43 2017-01-30T12:43:34,754775510-0500-foo
    jep at colug:~/stuff $ backup 
    mv: cannot stat ‘[a-z]*’: No such file or directory
    jep at colug:~/stuff $ 

In this example the complaint from mv causes no problem,
but it would be better for the loop to not execute
the body when there are no matching files.



More information about the colug-432 mailing list