Although the following command returns an exit status that depends on the existence of the remote file:
ssh $userAtServer "ls $targetDir/$targetFile" > $sshOutputFile
lsReturnValue=$?
which I can then test to do some stuff, it sometimes hangs (1 out of 10 or 20) and blocks further code execution.
So I need to run a ssh command like this one and to retrieve the exit value of the ls function:
(ssh $userAtServer "ls $targetDir/$targetFile" > $sshOutputFile ; lsReturnValue=$?) &
timeOutProcess $!
However, lsReturnValue always return an empty string.
timeOutProcess is a function that kills my command if it lasts for too much time:
timeOutProcess() {
processId=$1
#from http://www.bashcookbook.com/bashinfo/source/bash-4.0/examples/scripts/timeout3
timeout=45
interval=2
delay=5
(
((t = timeout))
while ((t > 0)); do
sleep $interval
kill -0 $processId || return 0
((t -= interval))
done
# Be nice, post SIGTERM first.
# The 'exit 0' below will be executed if any preceeding command fails.
kill -s SIGTERM $processId && kill -0 $processId || exit 0
sleep $delay
kill -s SIGKILL $processId
) 2> /dev/null
}
I wonder how could I get the $? value from the ssh command ?
lsReturnValue
is being set inside a subshell (the parenthesis,()
), you cannot access it outside the subshell. Also there is atimeout
command in just about every Linux distro, so you don't have to write your owntimeOutProcess
function.timeout
command info