Skip to main content
1 of 4
Gilles 'SO- stop being evil'
  • 865.9k
  • 205
  • 1.8k
  • 2.3k

Why does my shell script choke on whitespace or other special characters?

Or, an introductory guide to robust filename handling and other string passing in shell scripts.

I wrote a shell script which works well most of the time. But it chokes on some inputs (e.g. on some file names) — I encountered a problem such as the following:

  • I have a file name containing a space hello world, and it was treated as two separate files hello and world.
  • I have an input line with two consecutive spaces and they shrank to one in the input.
  • Leading and trailing whitespace disappears from input lines.
  • Sometimes, when the input contains one of the characters \[*?, they're replaced by some text which is is actually the name of files.
  • There's an apostrophe ' (or a double quote ") in the input and things got weird after that point.
  • There's a backslash in the input (or: I'm using Cygwin and some of my file names have Windows-style \ separators).

What's going on and how do I fix it?

Gilles 'SO- stop being evil'
  • 865.9k
  • 205
  • 1.8k
  • 2.3k