3

I have a very basic question. I'm running a Ruby script to access the contents of a directory in Linux. The directory is passed through the command line when the ruby script is executed.

My question is how would I use the command line argument in the command for ruby?

I have it set like such:

usrDirectory = ARGV[0]
lsCmd = `ls -l`

I need to use something like ls -l usrDirectory. Could I just insert it into the command like is?

4 Answers 4

2

The above is right, and if you want to have ls output to standard out, this makes it a little cleaner:

system("ls", "-l", dir)

This will make Ruby print the output to your standard out instead of putting the output in the variable as the above does.

Sign up to request clarification or add additional context in comments.

1 Comment

If you're going to use system you should use the multi-argument version: system('ls', '-l', dir)
1

You should be able to get what you want without using the shell, for example:

usr_dir = "/tmp"
files = Dir["#{usr_dir}/*"]

p files

No matter what you do, be Very Careful when passing text entered by an user to the shell as part of something that will get parsed and executed. For example, what happens if the user enters (instead of a directory name)

;rm -rf /*

?

3 Comments

That's why you use the multi-argument versions of these commands, they bypass the shell and use your arguments directly as the arguments for the program.
Yes, the point is don't let the shell parse it. Way too much power.
Exactly. I'm pretty sure we agree.
0

You can use expression expansion and escape sequences in the command string:

lsCmd = `ls -l #{usrDirectory}`

Comments

0

You have two options. You can do:

lsCmd = `ls -l #{usrDirectory}`

or

command = "ls -l " + usrDirectory
lsCmd = %x[ #{command} ]

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.