如何检查外部shell脚本退出代码

时间:2012-11-20 18:45:41

标签: bash shell ftp

我有一个简单的“主”shell脚本,可以执行一些准备工作,然后调用另一个将脚本上载到ftp站点的shell脚本。我想知道如何等待并检查被调用shell脚本的退出代码,以及如何轻松检查FTP文件是否实际成功上传并提供正确的退出代码(0或1)

谢谢

主脚本:

#!/bin/sh
# check for build tools first
FTP_UPLOAD_SCRIPT=~/Desktop/ftp_upload.sh

if [ -f "$FTP_UPLOAD_SCRIPT" ]; then
    echo "OK 3/5 ftp_upload.sh found. Execution may continue"
else
    echo "ERROR ftp_upload.sh not found at $FTP_UPLOAD_SCRIPT. Execution cannot continue."
exit 1
fi

  # upload the packaged installer to an ftp site
  sh $FTP_UPLOAD_SCRIPT

  # check the ftp upload for its exit status
  ftp_exit_code=$?
  if [[ $ftp_exit_code != 0 ]] ; then
    echo "FTP ERRORED"
    exit $ftp_exit_code
  else
    echo $ftp_exit_code
    echo "FTP WENT FINE"
  fi

  echo "\n"
  exit 0

ftp_upload_script:

#!/bin/sh
FTP_HOST='myhost'
FTP_USER='myun'
FTP_PASS='mypass'

FTPLOGFILE=logs/ftplog.log
LOCAL_FILE='local_file'
REMOTE_FILE='remote_file'

ftp -n -v $FTP_HOST <<SCRIPT >> ${FTPLOGFILE} 2>&1
quote USER $FTP_USER
quote PASS $FTP_PASS
binary
prompt off
put $LOCAL_FILE $REMOTE_FILE
bye
SCRIPT
echo $!

2 个答案:

答案 0 :(得分:3)

我认为您要查找的内容是exit $?,而不是FTP脚本底部的echo $!

使用echo只会打印到stdout,但不会返回退出代码(因此应使用exit)。特殊$?是前一个流程的返回代码,而不是$!,即流程ID。

答案 1 :(得分:0)

我提出了一个解决方案,它既可以检查ftp上传,又可以提供适当的退出代码。

... ftp upload first ... then ...

# this is FTP download double-check test
ftp -n -v $FTP_HOST <<SCRIPT >> ${FTPLOGFILE} 2>&1
quote USER $FTP_USER
quote PASS $FTP_PASS
binary
prompt off
get $REMOTE_FILE $TEST_FILE
bye
SCRIPT

#check to see if the FTP download test succeeded and return appropriate exit code
if [ -f "$TEST_FILE" ]; then
  echo "... OK FTP download test went fine. Execution may continue"
  exit 0
else
  echo "... ERROR FTP download test failed. Execution cannot continue"
  exit 1
fi