Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to validate a terminal command has run successfully in Rails?

I'm writing a quick Rails app and was wondering how I can validate the success an exec'd command. The two commands I'm running are and SVN update, and a cp from one directory to another.

like image 396
Devar-TTY Avatar asked Oct 05 '08 01:10

Devar-TTY


3 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 different ruby system commands here.

like image 146
Gordon Wilson Avatar answered Nov 16 '22 10:11

Gordon Wilson


How are you executing the external commands? The Ruby system() function returns true or false depending on whether the command was successful. Additionally, $? contains an error status.

like image 28
Greg Hewgill Avatar answered Nov 16 '22 10:11

Greg Hewgill


  1. Just to be pedantic, you can't validate an exec'd command because exec replaces the current program with the exec'd command, so the command would never return to Ruby for validation.
  2. For the cp, at least, you would probably be better of using the FileUtils module (part of the Ruby Standard Library), rather than dropping to the shell.
  3. As noted above, the $? predefined variable will give you the return code of the last command to be executed by system() or the backtick operator.
like image 1
Avdi Avatar answered Nov 16 '22 12:11

Avdi