Friday, July 13, 2012

NBSP versus SP: The non breaking space which breaks

Yup the Non Break Space (NBSP) character (octal 240, hex A0, dec 160) does not play good with scripts. Sometimes you copy and paste snippets of code from websites like Thinking In Software and the code simply does not work and you get errors like:
'\240`: command not found
Clearly you need to clean the code and here is one of the methods to do so. It is just a POB as usual:
#!/bin/bash -e
# nbsp2sp.sh
filePath=$1
USAGE="Usage: `basename $0` <filePath>"
if [ $# -ne "1" ]
then
echo $USAGE
exit 1
fi
tr '\240' ' ' < $filePath > /tmp/tmp && mv /tmp/tmp $filePath
view raw nbsp2sp.sh hosted with ❤ by GitHub
The character combination \302\240 (U+00A0) is usually found as well when copying code from websites.

However if you are serious about posting code snippets I recommend using gist. Just paste your code or add modifications in the future. You can copy the content from "Embed this gist" which is a script tag you can directly paste in your blog. The code above is coming from nbsp2sp.sh gist.

No comments:

Followers