有没有参数可以让脚本遇到错误时自动终止?

sh/bash/dash/ksh/zsh等Shell脚本
回复
头像
5451vs5451
帖子: 345
注册时间: 2006-07-14 18:56
来自: Apple Valley, Planet Tux, Linux System

有没有参数可以让脚本遇到错误时自动终止?

#1

帖子 5451vs5451 » 2006-08-23 12:32

#!/bin/sh
rm
rm

执行第一个rm命令会出错,就没有必要再执行第二条rm了。
头像
laborer
帖子: 1016
注册时间: 2005-10-25 11:15
联系:

#2

帖子 laborer » 2006-08-23 21:45

用cmd1 && cmd2,e.g.

代码: 全选

$ true && echo hi
hi
$ false && echo hi
hreiser@oakland:~$ killall -9 wife
police@oakland:~$ sudo find / -user hreiser
court@oakland:~$ sudo mv /home/hreiser /jail/
court@oakland:~$ sudo usermod -d /jail/hreiser -s "/usr/sbin/chroot /jail/" hreiser
头像
5451vs5451
帖子: 345
注册时间: 2006-07-14 18:56
来自: Apple Valley, Planet Tux, Linux System

#3

帖子 5451vs5451 » 2006-08-23 22:44

遇到exit就不好用了,例如
true && echo hi; exit
exit每次都会执行,如果加上括号
true && (echo hi; exit)
exit只退出子进程
头像
laborer
帖子: 1016
注册时间: 2005-10-25 11:15
联系:

#4

帖子 laborer » 2006-08-23 22:51

那就

代码: 全选

false || exit
echo hi
[/code]
hreiser@oakland:~$ killall -9 wife
police@oakland:~$ sudo find / -user hreiser
court@oakland:~$ sudo mv /home/hreiser /jail/
court@oakland:~$ sudo usermod -d /jail/hreiser -s "/usr/sbin/chroot /jail/" hreiser
头像
5451vs5451
帖子: 345
注册时间: 2006-07-14 18:56
来自: Apple Valley, Planet Tux, Linux System

#5

帖子 5451vs5451 » 2006-08-23 23:10

laborer 写了:那就

代码: 全选

false || exit
echo hi
[/code]
哦,知道了,谢谢。
windforest
帖子: 53
注册时间: 2005-12-13 20:56
联系:

#6

帖子 windforest » 2006-08-27 8:21

set -e Exit immediately if a command exits with a non-zero status.
回复