Things To Remember – Part 1 (space in file name, return value)

This time it’s just a little reminder – probably first one of a series!

Spaces In File Name

When writing a script that will have to operate on files it’s more than likely that you’ll get a file with spaces in the name and then your script – out of doubt – it will fail.

To prevent this happening I tend to use one of these two solutions:

  1. find /somepath -iname somename | while read f; do echo “Processing: $f…”; done;
    This way we can use read - that will do all the dirty work for you. making sure all of the spaces are escaped.
  1. Shell needs to know what char will separate the arguments or commands and it needs to store it somewhere too. Since the char is space (what a surprise!) and we know that the variable $IFS stores it, we can simply replace it with whatever we need at the moment. In my case it was a new line char, which I’ve assigned this way:

    SAVEIFS=$IFS;

    IFS=’

    ‘;

    but because we don’t want to lose the original value of $IFS we need to assign it to another variable first and then replace with a new value. Then when the script – or the part of it that needed the change – is done, the old value should be restored:
    IFS=$SAVEIFS;

 

Additionally it’s always a good idea to wrap variable containing a file name in “double quotes”.

Returned value

Another useful feature that may be not used often enough is checking what value the last command has returned – this is something that will tell you wherever it’s succeeded – or failed dreadfully – and you can retrieve it from this variable

$?

So echo $? will print most likely 0 or 1, where 0 means success and 1 error, it can return other codes as well but then you’ll need to refer to documentation for this particular command.

This entry was posted in Managed Hosting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>