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, June 09, 2006

    Playing cat and mouse with the cat builtin

    Teaching Fundies. Using cat. Straightforward, hey?

    One example in the book says, that you cannot redirect file onto itself using cat.
    What should happen is:

    $ cat file5 > file5
    cat: file5: input file is output file

    Delegates try this - "Alina, it doesn't work!". What does happen is:

    $ cat file5 > file5

    Several minutes of experimenting, and one of the delegates shouted with satisfaction: "Got it - cat is a built in".

    What? As surprised as I was, in the ksh-20050202-1 cat is a builtin, in addition to the standard /bin/cat.

    $ type cat
    cat is a shell builtin version of /bin/cat

    It may be a builtin implementation of /bin/cat, but there is behavioural difference. Perhaps not because of changes to what or how the two cat versions work, but due to the fact that one (the builtin) is operating in the same process as the calling shell, the other (/bin/cat) gets its own process space.

    This could have VERY serious implications for shell scripts!

    Consider the following:

    $ cat x > x
    $ echo $?

    Then try the same, this time using external version:

    $ /bin/cat x > x
    /bin/cat: x: input file is output file
    $ echo $?

    How many programmers use full pathnames in their scripts? If you are one of them – well done, and you will have no problems with this particular cat!

    If not, however (admit it!), any script written in the past, that uses cat's exit status will fail when ported to this version of ksh.

    OK, so why would you like to use cat for testing? I don't know – but that's not the point!

    No comments:

    Blog Archive