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:
- 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.
- 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.