Friday, December 17, 2010

Shell escaped file names in ruby

When files have crazy characters in their filename (like ' or ""), it can make creating a robust script challenging. After all, if you write the script with either a single quotation mark or a double quotation mark, the other one will trip you up:


file1 = "my'crazy'file.txt"
file2 = 'my"crazy"file.txt'
system "mv \"#{file2}\" bettername.txt"  # fails on file2
system "mv '#{file2}' bettername.txt"    # fails on file1

The answer is to use the multiple arguments invocation, which will properly escape your filename to be fully shell compatible:

system "mv", file1, "bettername.txt"  # works on file1 or file2

2 comments:

Unknown said...

It's also possible to use shellwords standard library for this reason.
http://www.ruby-doc.org/stdlib-2.1.5/libdoc/shellwords/rdoc/Shellwords.html

JTP said...

You're right, Ilya. I use shellwords in my scripts most of the time--very handy library!