How to get exit status of R script run in shell script - r

Suppose I'm running a Rscript from inside this shell script
#!/bin/bash
RES=$(./abc.R 100)
r_status=echo $?
There is some code in abc.R which stops its execution
#!/usr/bin/env Rscript
...
...
if(nrow(status) == 0)
{ stop("The list id is not present in requests table. Please check.") } else if (status != 'COMPLETED')
{ stop("The list is not in COMPLETED state. Please check.")}
...
...
I am not able to capture the exit status of abc.R in my shell script. It stops R execution and even quits from the shell script to the prompt.
Is there any way I can capture R's exit status.

Just run the script you want.
make sure it returns the correct exit status when finishing its run.
This should work:
#!/bin/bash
./abc.R 100
if [ $? == 0 ]; then
echo "Your script exited with exit status 0"
exit 0
see more here:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_08_02.html

Related

How to fix error message in tcl script having command [exec bjobs] when no jobs are running?

when I am running a Tcl script that contains the following lines:
set V [exec bjobs ]
puts "bjobs= ${V}"
When jobs are present it's working properly but, no jobs are running it is showing an error like this:
No unfinished job found
while executing
"exec bjobs "
invoked from within
"set V [exec bjobs ]"
How to avoid this error? Please let me know how to avoid this kind of errors.
It sounds to me like the bjobs program has a non-zero exit code in this case. The exec manual page includes this example in a subsection WORKING WITH NON-ZERO RESULTS:
To execute a program that can return a non-zero result, you should wrap
the call to exec in catch and check the contents of the -errorcode
return option if you have an error:
set status 0
if {[catch {exec grep foo bar.txt} results options]} {
set details [dict get $options -errorcode]
if {[lindex $details 0] eq "CHILDSTATUS"} {
set status [lindex $details 2]
} else {
# Some other error; regenerate it to let caller handle
return -options $options -level 0 $results
}
}
This is more easily written using the try command, as that makes it
simpler to trap specific types of errors. This is done using code like
this:
try {
set results [exec grep foo bar.txt]
set status 0
} trap CHILDSTATUS {results options} {
set status [lindex [dict get $options -errorcode] 2]
}
I think you could write this as:
try {
set V [exec bjobs ]
} trap CHILDSTATUS {message} {
# Not sure how you want to handle the case where there's nothing...
set V $message
}
puts "bjobs= ${V}"
if {[catch {exec bjobs} result]} {
puts "bjobs have some issues. Reason : $result"
} else {
puts "bjobs executed successfully. Result : $result"
}
Reference : catch
Note carefully in the exec man
page:
If any of the commands in the pipeline exit abnormally or are killed or
suspended, then exec will return an error [...]
If any of the commands
writes to its standard error file and that standard error is not
redirected and
-ignorestderr is not specified, then exec will return an
error.
So if bjobs returns non-zero or prints to stderr when there are no jobs, exec needs catch or try as Donal writes.

Running Autoit from command line and see errors/results

I am trying to run some autoit.au3 script from command line and see results there. I have put some ConsoleWrite inside script and also Exit(1) but after I run script nothing is shown in console. It just stop script on Exit and ConsoleWrite is not displayed.
I have use command:
"C:...(path to my AutoIt3.exe)" /ErrorStdOut "path_to_my_script.au3"'
Also I have tried to run script.exe with this same command but with similar (no) result. I would like to see output in console and/or custom error messages when script fail (I don't know if that is possible).
AutoIt3.exe is a GUI program. So the STD streams of a GUI program are not printed at a console by default.
The /ErrorStdOut argument redirects errors messages to Console instead of a Msgbox.
This argument does not enable print at the Console.
Command Prompt:
To print at a Command Prompt, you could pipe to more, i.e.
"C:...(path to my AutoIt3.exe)" /ErrorStdOut "path_to_my_script.au3" 2>&1|more
more reads from the Stdin stream and prints to Console.
I intentionly added 2>&1 so the Stderr stream is merged with
Stdout so you get the merged streams printed.
If you do not want the errors, then you can redirect the Stderr stream to nul i.e.
replace 2>&1 with 2>nul.
If you used a for loop at a Command Prompt, it would be i.e.
for /f "delims=" %A in ('"C:...(path to my AutoIt3.exe)" /ErrorStdOut test1.au3') do echo %A
If you use the for loop in batch-file, use %%A instead of %A. To also capture the Stderr, insert 2^>&1 into the for command or to ignore, insert 2^>nulinto the for command i.e.
for /f "delims=" %A in ('2^>nul "C:...(path to my AutoIt3.exe)" /ErrorStdOut test1.au3') do echo %A
The previous methods will not get the Exitcode.
AutoIt code:
An AutoIt script can get the Stdout and the Exitcode.
#pragma compile(Out, 'consoleau3.exe')
#pragma compile(Console, True)
$sAutoit = 'C:...(path to my AutoIt3.exe)'
$iPid = Run('"' & $sAutoit & '" /ErrorStdout ' & $CMDLINERAW, '', #SW_SHOW, 2) ; 2 = Get Stdout stream.
If #error Then Exit
; Open process handle.
$hPid = _ProcessOpenHandle($iPid)
; Get Stdout stream and then print to Console.
$sStdout = ''
Do
Sleep(10)
If $sStdout Then ConsoleWrite($sStdout & #CRLF)
$sStdout = StdoutRead($iPid)
Until #error
; Require process to be closed before calling _ProcessGetExitCode()
ProcessWaitClose($iPid)
; Get exitcode of process.
$iExitcode = _ProcessGetExitCode($hPid)
; Close process handle.
_ProcessCloseHandle($hPid)
Exit $iExitcode
Func _ProcessOpenHandle($iPID)
; Get the process handle of the process to query\n Return: Success Handle as array. Failure 0
Local Const $PROCESS_QUERY_INFORMATION = 0x400
Local $hPID = DllCall('kernel32.dll', 'ptr', 'OpenProcess', 'int', $PROCESS_QUERY_INFORMATION, 'int', 0, 'int', $iPID)
If #error Then Return SetError(#error, #extended, 0)
Return $hPID[0]
EndFunc
Func _ProcessGetExitcode($hPID)
; Get exitcode of the closed process\n Return: Success Exitcode as integer. Failure 0
Local $vPlaceholder
$hPID = DllCall('kernel32.dll', 'ptr', 'GetExitCodeProcess', 'ptr', $hPID, 'int*', $vPlaceholder)
If #error Then Return SetError(#error, #extended, 0)
Return $hPID[2]
EndFunc
Func _ProcessCloseHandle($hPID)
; Close the handle of a process\n Return: Success 1. Failure 0
DllCall('kernel32.dll', 'ptr', 'CloseHandle', 'ptr', $hPID)
If #error Then Return SetError(#error, #extended, 0)
Return 1
EndFunc
Correct the path to AutoIt.exe in the code.
Compile to AutoIt code to executable. It will be a Console program
and will be named consoleau3.exe as to the #pragma compile directives.
Usage:
consoleau3 "path_to_my_script.au3"
Script arguments can be added i.e.
consoleau3 "path_to_my_script.au3" arg1 arg2 arg3 ...

UNIX Why does this command not exit my program?

I am trying to get this program to exit if it cannot find the file that has to be deleted. Or if it won't delete for any reason.
When I use this it runs my program it gives me an error "cannot find file" and completes my program successfully.
del `unixpath2win filename`
rc=$?
if [ $rc -ne 0 ] ; then
echo_c $1 "error with deletion of filename"
checkrc.sh $rc
exit 1
fi

Error handling in unix shell ksh

Can anyone guide to a document or explain on the below
how to use error handling in ksh.
How does Unix work on unhandled errors(like error happened in the
subscript etc..).
From ksh man page.
Unhandled errors
Errors detected by the shell, such as syntax errors, cause the shell to return a non-zero exit status. If the shell is being used
non-interactively, then execution of the shell
file is abandoned UNLESS the error occurs inside a subshell in which case the subshell is abandoned.
Error handling
Basically check exit/return codes to handle errors:
if [ $exit_code != 0 ]; then
# Your error handler
fi
Example
test_handler() {
ls file_not_present
if [ $? -eq 2 ]; then
echo "Handler for No such file or directory"
elif [ $? -ne 0]; then
echo "Handler for any other exception"
else
echo "Succesful execution"
fi
}
Will throw:
ls: cannot access non_file: No such file or directory
Handler for No such file or directory
But if the command does not exit:
test_handler() {
l file_not_present
if [ $? -eq 2 ]; then
echo "Handler for No such file or directory"
elif [ $? -ne 0 ]; then
echo "Handler for any other exception"
else
echo "Succesful execution"
fi
}
The output will be:
l: not found [No such file or directory]
Handler for any other exception
The shell returns
the exit status of the last command executed
(see also the exit command above). Run time errors detected by the shell are reported by printing the command or function name and
the error condition. If the line number that
the error occurred on is greater than one, then the line number is also printed in square brackets ([]) after the command or function
name.

exit function gets skipped in Unix Shell script

I have the following as part of my code. But when it reaches this if block, if the condition evaluates to true, the print function is getting executed but the exit function is not. It just gets skipped. Is it because of some mistake in the if condition? Or will I have to share my full code?
if ( grep -i ERROR /tmp/swm_pkg_ros )
then
print "\nFailed. ...EXITING"
print "\n....you will need to fix the problem and rerun\n"
exit
else
print "Successful"
fi
It works fine for me:
if ( grep -i ERROR /tmp/swm_pkg_ros )
then
echo -e "\nFailed. ...EXITING\n....you will need to fix the problem and rerun"
exit 1
else
echo "Successful"
fi
you may print exit code echo $?

Resources