Variables with spaces used in external command

I’m a Ruby newb, so this is probably not coded in the most efficient
manner.

I’m trying to read through a list of folder and convert my wav files to
flac. The below code works with most files but some blow up and break at
spaces and I can’t figure out where my error is. This worked for most of
the files in my folder.

Dir.glob(".wav") do |filename|
mybasename = File.basename("#{filename}",’.
’)
mybasename += “.flac”
puts “Calling avconv -i ‘#{filename}’ ‘#{mybasename}’”
%x[avconv -i ‘#{filename}’’#{mybasename}’]
end

My output looks like this:
Calling avconv -i ‘02-11 - When It’s Gone.wav’ ‘02-11 - When It’s
Gone.flac’
avconv version 9.16-6:9.16-0ubuntu0.14.04.1, Copyright © 2000-2014 the
Libav developers
built on Aug 10 2014 18:16:02 with gcc 4.8 (Ubuntu 4.8.2-19ubuntu1)
02-11 - When Its: No such file or directory

Did you type that out manually or copy it directly? You’re missing the
space between “’#{filename}’’#{mybasename}’”
There should be a space between the middle “’” characters.

You’re also using single quotes / apostrophes around a string containing
the same character. If you take “When it’s” and surround it with two “’”
characters, that’s 3 single quotes, making it terminate incorrectly.

Thanks for replying Joel.

Good eyes on the space, i’d been playing around with spacing thinking
that might be the cause, which it’s not.

What should I surround the variable with if it contains a apostrophes
and spaces ?

If I use double quotes, it breaks on spaces and the file-name ends up
being something like the example of “02-11 - When its” instead of "02-11

  • When It’s Gone.wav". Although this looks like an issue with the
    apostrophe rather than a space.

FCC

I’m no expert on on ubuntu, but if it won’t let you use double quotes,
have you tried escaping the space with “”? (or escaping the quote)

It seems like i’m at an impasse. If I don’t use a single quote, it
breaks on spaces and if I use a single quote it breaks on an apostrophe.

I don’t think I can escape anything since i’m passing the string to bash
to run avconv.

Does this help? http://wiki.bash-hackers.org/syntax/quoting

Thanks for all you of your replies and suggestions. I think I’ve found
my solution.

Shellwords
http://www.rubydoc.org/stdlib1.9.3/libdoc/shellwords/rdoc/Shellwords.html

I’m not sure how I didn’t stumble on this before, but the shellescape
option looks like it should be used for all output you are trying to
pass to bash.