Twitter Updates

    follow me on Twitter

    G-AVLN in front of her home

    G-AVLN in front of her home

    Mostly Unix and Linux topics. But flying might get a mention too.

    Wednesday, October 24, 2007

    An example of using eval

    When learning (or teaching) eval, the first - and very valuable - example of it is to see eval's ability to evaluate the value of the last positional parameter:

    $ set a b c d

    $ eval print -- \$$#

    d


    We use eval it to force the shell to perform a double scan, when we need to find a value of a value. First scan will evaluate the $# to the number of available parameters (in this case: 4); the second scan will check the value of it (d). This is 'bread and butter' of eval application.

    Other cases of using eval are a bit more obscure, and for that reason eval is often forgotten...

    Here is an example that is not 'that' obscure - and possible quite useful. A delegate wanted to rename all files in a given directory, to change the character case from lower to upper. What he devised, successfully, is as follows:

    for file in *

    do

    mv $file $(echo $file | tr '[a-z]' '[A-Z]')

    done



    This worked, until he found that some of the files contained 'unfriendly' characters: spaces. The script failed to cope with this.

    This is where eval stepped in:

    for file in *

    do

    eval mv '"$file"' \"$(echo "$file" | tr '[a-z]' '[A-Z]' )\"


    done

    In this case eval allows to insert an additional set of double quotes, which protected spaces embedded in file names.

    No comments:

    Blog Archive