Reputation: 35
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?
Upvotes: 3
Views: 1355
Reputation: 35803
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.
Upvotes: 2
Reputation: 29615
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 /*
?
Upvotes: 1
Reputation: 46943
You have two options. You can do:
lsCmd = `ls -l #{usrDirectory}`
or
command = "ls -l " + usrDirectory
lsCmd = %x[ #{command} ]
Upvotes: 0
Reputation: 96258
You can use expression expansion and escape sequences in the command string:
lsCmd = `ls -l #{usrDirectory}`
Upvotes: 0