首页 > 解决方案 > 不明白为什么我们的函数调用返回两次?

问题描述

我们有一个 15 年(左右)的旧剧本,我们正试图找出并记录下来。我们在其中发现了一些错误,但是一个特定的日志文件让我们非常头疼。我希望得到一些帮助来解决这个问题。首先是与问题一起运行的函数:

#=========================================================#
# Define function removeOldBackupFile.                    #
#=========================================================#
removeOldBackupFile()
{
#set -x
  echo "Removing old backups if they exists." >> "${report}"
  local RCLOC=0
  spaceBefore=$(getAvailableSpace ${backupDirectory})
  timesToWait=60 # Wait a maximum of 10 minutes before bailing

  cat ${oldDbContainer} | while read fileName
  do
    echo "Old file exists. Removing ${fileName}." >> "${report}"
    removeFileIfExist "${fileName}"
    RC=$?
    echo "Resultcode for removing old backup is: RC=$RC." >> "${report}"
    RCLOC=$(($RC+$RCLOC))
    spaceAfter=$(getAvailableSpace ${backupDirectory})

    # Wait for the OS to register that the file is removed
    cnt=0
    while [ $spaceAfter -le $spaceBefore ]; do
      cnt=$((cnt+1))
      if [ $cnt -gt $timesToWait ]; then
        echo "Waited too long for space in ${backupDirectory}" | tee -a "${report}"
        RCLOC=$(($RCLOC+1)) 
        return $RCLOC
      fi
      sleep 10 
      spaceAfter=$(getAvailableSpace ${backupDirectory})
    done
  done

  return $RCLOC
}

运行这个函数的地方如下:

#=========================================================#
# Remove old backupfiles if any exist.                    #
#=========================================================#
  removeOldBackupFile
  RC=$?
  RCSUM=$(($RC+$RCSUM))

我们发现 if 条件有点错误,如果有多个文件,while 循环将无法按预期工作。

但困扰我们的是日志文件的输出:

...
+ cnt=61
+ '[' 61 -gt 60 ']'
+ echo 'Waited too long for space in /<redacted>/backup'
+ tee -a /tmp/maintenanceBackupMessage.70927
Waited too long for space in /<redacted>/backup
+ RCLOC=1
+ return 1
+ return 0
+ RC=0
+ RCSUM=0
...

正如在内部循环运行 60 次并结束后的日志输出中所见,它按预期返回 1.. 但是!它也有返回0之后!?为什么它也返回0?

我们无法计算出双重回报......任何帮助

标签: bashreturn

解决方案


第一个return在由 pipe 启动的子shell 中执行cat ${oldDbContainer} | while ...。第二个返回来自return $RCLOC函数的末尾。摆脱无用的使用cat

removeOldBackupFile()
{
#set -x
  echo "Removing old backups if they exists." >> "${report}"
  local RCLOC=0
  spaceBefore=$(getAvailableSpace ${backupDirectory})
  timesToWait=60 # Wait a maximum of 10 minutes before bailing

  while read fileName
  do
    ...
  done < ${oldDbContainer}

  return $RCLOC
}

推荐阅读