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.

    Friday, October 21, 2005

    Commenting out a block of lines in a script

    Everybody knows of the '#' character as the character allowing to comment out lines that are not meant to be interpreted by the shell in a shell script.

    Well, how cumbersome and untidy it ends up sometimes! Imagine you have a block of code, perhaps a big for-do-done loop, or a complex if-elif-else-fi statement and you need to, temporarily, take it out of the script for some reason. Inserting hash in front of each line, and then removing it again when done with whatever test you wanted to conduct is just plain messy.

    Ok, you could argue that this can be done nicely in vi :

    First, identify line numbers with:

    :set nu


    :10,30s/^/# /

    will insert the hash at the begining of line, on lines 10 through 30, but even this is long-winded, and if you are using another editor, then the method may not be available at all.

    The alternative is to use a combination of the 'do nothing' command: the colon command, and the 'here document'. Imagine the following construct:

    : <<>

    You can easily move the two lines up and down the script, and isolate the blok of line you don't want to 'participate' at run time.

    How does it work? The colon command means 'do nothing', but generate exit status 0, success. The way we are using it here is: 'do nothing, and whilst doing this ;-) use stream of data provided as 'here document'. This embedded data is not not interpreted by the shell at run time, so it hides our code!

    No comments:

    Blog Archive