Ruby system call

I am new to ruby ​​and programming, and also need help with a system call to move a file from source to destination as follows:

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

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

+6
ruby system
source share
4 answers

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

can be replaced by

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

which reduces the chances of a command line injection attack.

+11
source share

Two ways

Recommended Method

You can use the functions in the File Utils library, see here to move your files, for example.

 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 line as a command)

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

Well, this is just a variation of calling the system command, but it looks a lot prettier!

+9
source share
 system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file}) 

must be the right call

+3
source share

I recommend you use Tanaka akira escape library Here is an example from one of my applications:

 cmd = Escape.shell_command(['python', Rails::Configuration.new.root_path + '/script/grab.py']).to_s system cmd 
+1
source share

All Articles