0

The following code includes a command and a string:

files = `ls /tmp`

I would like /tmp to be a variable instead of a static string, and would ideally like it to be like:

dir = '/tmp'
command = 'ls ' + dir
files = `command`

What is the correct Ruby syntax to achieve this?

3
  • 3
    I hope this shouldn't need saying, but be VERY careful about accepting user input if you're going to execute it blindly in a shell Commented Apr 18, 2013 at 14:19
  • There are some great examples using string interpolation in this great card I've been recommended yesterday. Commented Apr 18, 2013 at 14:27
  • thanks folks, shall do Commented Apr 18, 2013 at 18:28

3 Answers 3

3

Use string interpolation:

dir   = '/tmp'
files = `ls #{dir}`
Sign up to request clarification or add additional context in comments.

Comments

2
files = `#{command}`

Is that what you are looking for ?

Comments

2

Use the standard shellwords library. It will take care of proper escaping, which will help to protect you from shell injection attacks.

require 'shellwords'

command = [
  'ls',
  dir
].shelljoin
files = `#{command}`

If dir comes from untrusted input, the above code still allows someone to see any directory on your system. However, using shelljoin protects you from someone injecting, for example, a "delete all files on my hard drive" command.

In the particular case of listing a directory, The built-in class Dir will do that rather well:

files = Dir[File.join(dir, '*')]

Here we add a glob onto the end of the directory using File::join. Dir::[] then returns the paths of the files in that directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.