Bash 脚本退出状态以说明 git 重置

Bash script exit status to account for a git reset

我有一个用于部署 AWS beanstalk 应用程序的脚本。脚本的早期部分根据我正在部署的环境修改了一些文件:

if [[ $enviro == qa ]] || [[ $enviro == staging ]]; then
  sed -i '' 's/'$app'.config/'$app'-'$enviro'.config/g' .ebextensions/0006_file.config
  git add .ebextensions/0006_file.config && git commit -m " for deploy only - will be (soft) reset "
fi

我的脚本的最后一点恢复了:

if [[ $enviro == qa ]] || [[ $enviro == staging ]]; then
  git reset --soft HEAD~1
  git reset HEAD .ebextensions/0006_file.config
  git checkout .ebextensions/0006_file.config
fi

但是在这两个块之间我有实际的部署线:

eb deploy $app-$enviro --label $current_date-$current_user --timeout 30 -v

我想做的是编写一个 if/then 语句,如果 'eb deploy' 块因退出代码=1 而失败但也会退出脚本 git 重置。如果脚本 'eb deploy' 块成功 I:

echo "Congratulations, you've deployed $branch to $enviro"

我不知道,但我可能想多了。我愿意接受建议。我的猜测是我的第二个块必须有另一个 [[ ]] 来设置 rc=$?

想法?

如果您有一些代码想要在脚本退出时 运行,即使它提前退出,您也可以使用 trap

# this code will get run when the script exits, whether via `exit` or falling
# off the bottom of the script
trap '
    git reset --whatever
' EXIT

'Trap' 让我走上了正确的道路,但我需要添加一个函数来完成这个过程。

function clean_up {
  if [[ $enviro == qa ]] || [[ $enviro == staging ]] || [[ $enviro == staging2 ]]; then
    git reset --soft HEAD~1
    git reset HEAD .ebextensions/0006_file.config
    git checkout .ebextensions/0006_file.config
  fi
}
fi
trap clean_up EXIT