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

为君一笑 提交于 2019-12-10 09:27:31

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/33566978/return-code-from-shell-script-run-from-putty-to-calling-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!