space: the final fronier .... in bash

Space: the final frontier. These are the voyages of intrepid bash scripter. His multi-hour mission: to explore strange new whitespace, to seek out new ways of escaping, to boldly go quote what no man has needed to quote before.

Last night I was confronted with something I don't generally relish: a bug in my code.

In this case the script essentially was intended to trigger some file copies based on the input in a web form.

Basically, the user plugs in some variables, including a path for the original files and submits.

The web fronted (PHP) passes this to a helper script (BASH), which then runs in the background.

Here is what I hadn't thought about: SPACES in the file path.

Took me a few hours to get everything straight and cleaned up.

Here are some lessons:

  • When using a variable in bash and it's not already inside quotes, put some quotes around it anyway: "${VAR}"
  • Sometimes quotes aren't enough (for example on the remote side of an rsync) and you need to quote, so make use of BASH's ability and escape them: ${VAR// /\ }
  • Sometimes you'll need to quote the quotes:\"${VAR}\"
  • Sometimes you're better off getting rid of the spaces, such as when creating a log file: ${VAR// //__}
  • Sometimes it all goes to hell, when trying to spawn a subprocess with it's code in quotes: nohup bash -c ".........", then you end up with various combinations of the above, but it's very easy to run out of options.

The last part is just stupidity on my part and could really be fixed by just creating a separate script to call.

Oh, well. I'm not fond of spaces today.