Opening Image Files with Gnome-Open via Ruby on Linux
Recently in Ruby I was trying to open an image file in script by doing something like this:
example_image_file = Shellwords.shellescape(example_image_file)
example_image_file = "~/folder1/tiger cub.jpg"
system("gnome-open #{example_image_file}")
As was pointed out in this stackoverflow post, Shellwords.shellescape escapes the tilde (~) along with the spaces. This causes gnome-open to go looking for a file name that literally has a tilde in it. The other issue is that the file name contains characters I want the shell to interpret (tilde) and things I don’t want it to interpret (spaces).
The solution is to use the multi-argument version of the system call as follows:
system("gnome-open", File.expand_path(example_image_file))
File.expand_path expands the leading tilde to prevent me from relying on the shell to do it and the multi-argument system call means I don’t have to worry about the shell's escaping issues.