Executing shell script commands in a Ruby script

I have a very simple question. I am running a Ruby script to access the contents of a directory on Linux. The directory is passed through the command line when ruby ​​script is executed.

My question is how to use command line argument in command for ruby?

I have it installed like this:

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

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

+3
source share
4 answers

The above right, and if you want the output to lsbe standard, this makes it a little cleaner:

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

This will cause Ruby to output the output to your standard instead of putting the output in a variable as described above.

+2
source

, , , :

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

p files

, , , , -, . , , ( )

; rm -rf/*

?

+1

You can use expression and escape sequences on the command line:

lsCmd = `ls -l #{usrDirectory}`
0
source

You have two options. You can do:

lsCmd = `ls -l #{usrDirectory}`

or

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

All Articles