为什么我的脚本在命令后突然退出? [英] Why does my script suddenly exit after a command?

查看:58
本文介绍了为什么我的脚本在命令后突然退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照以下说明为Dash生成文档集: http://kapeli.com/docsets .问题是,脚本在wget之后不会继续运行,并且似乎不会引发任何错误.当我将脚本复制到终端中时,一切正常.

I am trying to generate docsets for Dash following these instructions: http://kapeli.com/docsets. The problem is, that the script doesn't continue after the wget and doesn't appear to throw any errors. Everything works fine when I copy the script into the Terminal.

我正在使用MacOS 10.8.4和默认的bash.

I'm using MacOS 10.8.4 and the default bash.

#!/usr/bin/env bash
set -e

mkdir -p $1.docset/Contents/Resources/Documents/

echo "THIS RUNS"
wget -rkp -l3 -np -nH --cut-dirs=1 --directory-prefix="./"$1".docset/Contents/Resources/Documents/" $2
echo "THIS DOES NOT RUN"

sed "s/NAME/$1/g" template > $1.docset/Contents/Info.plist
touch $1.docset/Contents/Resources/docSet.dsidx
# (script continues) 

我查看了其他帖子,例如我的shell脚本在exec后停止,但是我不在这里使用 exec .

I looked at other posts like My shell script stops after exec but I'm not using exec here.

为什么脚本会退出?

推荐答案

您启用了 set -e aka errexit .

如果其中一个命令返回一个非零的退出代码,您的脚本将退出,并且哪个命令专门失败可能并不总是很明显:

Your script will exit if one of the commands returns a non-zero exit code, and it may not always be obvious which command specifically fails:

  • 某些人可能会打印出一个有用的错误,以识别自身和问题
  • 有些(例如 wget )可能会在输出的页面数中简要提及错误方式
  • 有些(例如 grep )可能根本不显示错误或任何输出,脚本只会退出
  • Some may print a helpful error identifying itself and the problem
  • Some (like wget) may briefly mention an error way back in pagefuls of output
  • Some (like grep) may not show errors or any output at all, the script just exits

要知道哪个命令导致了问题,请使用 -x xtrace 来运行脚本:

To know which command is causing a problem, run script with -x aka xtrace:

bash -x script.sh

或在脚本本身中添加 set -x :

set -x
set -e
...

这将使脚本打印出正在执行的每个命令,因此您可以看到哪个是最后一个.

This will cause the script to print out each command being executed, so you can see which one was the last.

如果要忽略命令的退出状态,可以添加 ||.正确:

If you would like to ignore the exit status of a command, you can add || true:

# Causes exit if you lack read permission on any directory
find . -name '*.sh' 

# Does not cause the script to exit
find . -name '*.sh' || true

如果希望在脚本中触发 set -e 时收到警报,则可以设置一个陷阱:

If you would like to be alerted when set -e would trigger in your script, you can set a trap:

#!/bin/bash
set -e
# Show error if commands exit with non-zero
trap 'ret=$?; echo "$0:$LINENO: Error: set -e triggered"; exit $ret' ERR
# Would have failed silently
grep doesnotexist /etc/passwd
echo "This does not run"

执行时:

$ ./foo
./foo:6: Error: set -e triggered

这篇关于为什么我的脚本在命令后突然退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆