Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System call in Ruby

Tags:

ruby

system

I'm a beginner in ruby and in programming as well and need help with system call for moving a file from source to destination like this:

system(mv "#{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file}")

Is it possible to do this in Ruby? If so, what is the correct syntax?

like image 373
Niklas Avatar asked Apr 09 '10 09:04

Niklas


2 Answers

system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file})

can be replaced with

system("mv", "#{@SOURCE_DIR}/#{my_file}", "#{@DEST_DIR}/#{file}")

which reduces the chances of a command line injection attack.

like image 135
Andrew Grimm Avatar answered Sep 29 '22 12:09

Andrew Grimm


Two ways

Recommended way

You can use the functions in the File Utils libary see here to move your files e.g

mv(src, dest, options = {})


Options: force noop verbose

Moves file(s) src to dest. If file and dest exist on the different disk 
partition, the file is copied instead.

FileUtils.mv 'badname.rb', 'goodname.rb'
FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true  # no error

FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true


Naughty way

Use the backticks approach (run any string as a command)

result = `mv "#{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file}"`

Ok, that's just a variation of calling the system command but looks much naughtier!

like image 29
Chris McCauley Avatar answered Sep 29 '22 11:09

Chris McCauley