Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return code from shell script run from PuTTY to calling batch file?

I would like to ask a question about how to apply PuTTY and control its return values. My setup is like this.

There's a xxxxx.bat file which contains PuTTY call with a ssh connection in the likes of:

putty.ext ssh 10.10.10.10 -l xxxx -pw yyyy -t -m wintest.txt

The file wintest.txt contains:

echo "wintest.txt: Before execute..."

/home/tede/n55115/PD/winlinux/RUN.lintest.bsh

echo "wintest.txt: After execute..."
echo $?

The file lintest.bsh contains various commands, what interests me is to be able to capture the return value of a specific command in the .bsh file, and call on that value from the bat file, to add it into an if loop with a warning, ie if $? (or %ERRORLEVEL - I don't know what would work) then BLABLA

I've read a lot of posts about this, but frankly this is my first time doing anything with .bat files so its all slightly confusing.

like image 339
onlyf Avatar asked Nov 06 '15 12:11

onlyf


1 Answers

First, do not use PuTTY for automation, use Plink (PuTTY command-line connection tool).

But even Plink cannot propagate the remote command exit code.

You can have the remote script print the exit code on the last line of its output (what you are doing already with the echo $?) and have the batch file parse the exit code:

@echo off

plink.exe putty.ext ssh 10.10.10.10 -l xxxx -pw yyyy -t -m wintest.txt > output.txt 2>&1

for /F "delims=" %%a in (output.txt) do (
   echo %%a
   set "SHELL_EXIT_CODE=%%a"
)

if %SHELL_EXIT_CODE% gtr 0 (
   echo Error %SHELL_EXIT_CODE%
) else (
   echo Success
)

But of course, you have to fix your script to return the exit code you want (the current code returns exit code of the previous echo command):

echo "wintest.txt: Before execute..."

/home/tede/n55115/PD/winlinux/RUN.lintest.bsh
EXIT_CODE=$?

echo "wintest.txt: After execute..."
echo $EXIT_CODE
like image 90
Martin Prikryl Avatar answered Oct 15 '22 19:10

Martin Prikryl