What is the best way to verify a terminal command has been successfully executed in Rails?

I am writing a quick Rails application and wondered how I can verify the success of the exec'd command. The two commands that I run are updating SVN and cp from one directory to another.

+6
ruby terminal validation ruby-on-rails system
source share
4 answers

If you use the Kernel.system () method, it will return a boolean indicating the success of the command.

result = system("cp -r dir1 dir2") if(result) #do the next thing else # handle the error 

There is a good comparison of the various ruby ​​system commands here .

+8
source share

How do you execute external commands? The Ruby system() function returns true or false depending on whether the command was successful. In addition, $? contains the error status.

+2
source share
  • To be pedantic, you cannot test the exec 'd command because exec replaces the current program with the exec ' d command, so the command will never return to Ruby for verification.
  • For cp, at least you will most likely be better off using the FileUtils module (part of the Ruby standard library) rather than abandoning the shell.
  • As stated above, the predefined variable $? will give you the return code of the last command that will be executed by system() or the backtick operator.
+1
source share

To upgrade SVN, check the version number before and after the upgrade.

 svn_start_version = IO.popen("svn info").readlines[4] `svn update` svn_end_version = IO.popen("svn info").readlines[4] if svn_end_version > svn_start_version "success" end 

For cp, you can check the file size in the source file equal to the copied file.

 source_file_size = IO.popen("du file1").readlines `cp file1 file2` dest_file_size = IO.popen("du file2").readlines if dest_file_size == source_file_size "success" end 
-4
source share

All Articles