简体   繁体   English

如何在 Bash 脚本退出之前运行命令?

[英]How to run a command before a Bash script exits?

If a Bash script has set -e , and a command in the script returns an error, how can I do some cleanup before the script exits?如果 Bash 脚本set -e ,并且脚本中的命令返回错误,我如何在脚本退出之前进行一些清理?

For example:例如:

#!/bin/bash
set -e
mkdir /tmp/foo
# ... do stuff ...
rm -r /tmp/foo

How can I ensure that /tmp/foo is removed, even if one of the commands in ... do stuff ... fails?我如何确保/tmp/foo被删除,即使... do stuff ...中的命令之一失败?

Here's an example of using trap: 以下是使用陷阱的示例:

#!/bin/bash -e

function cleanup {
  echo "Removing /tmp/foo"
  rm  -r /tmp/foo
}

trap cleanup EXIT
mkdir /tmp/foo
asdffdsa #Fails

Output: 输出:

dbrown@luxury:~ $ sh traptest
t: line 9: asdffdsa: command not found
Removing /tmp/foo
dbrown@luxury:~ $

Notice that even though the asdffdsa line failed, the cleanup still was executed. 请注意,即使asdffdsa行失败,仍会执行清理。

From the bash manpage (concerning builtins): bash页(关于内置):

trap [-lp] [[arg] sigspec ...] 陷阱[-lp] [[arg] sigspec ...]
The command arg is to be read and executed when the shell receives signal(s) sigspec. 当shell接收sigspec信号时,将读取并执行命令arg。

So, as indicated in Anon.'s answer , call trap early in the script to set up the handler you desire on ERR. 因此,正如Anon。的回答所示 ,在脚本的早期调用trap来设置ERR所需的处理程序。

From the reference for set : set的参考:

-e -e

Exit immediately if a simple command (see section 3.2.1 Simple Commands) exits with a non-zero status, unless the command that fails is part of an until or while loop, part of an if statement, part of a && or || 如果一个简单的命令(参见3.2.1简单命令)以非零状态退出,则立即退出,除非失败的命令是until或while循环的一部分,if语句的一部分,&&或||的一部分。 list, or if the command's return status is being inverted using !. 列表,或者如果使用!反转命令的返回状态。 A trap on ERR, if set, is executed before the shell exits. ERR上的陷阱(如果已设置)将在shell退出之前执行。

(Emphasis mine). (强调我的)。

sh version of devguydavid's answer . sh版本的devguydavid的答案

#!/bin/sh
set -e
cleanup() {
  echo "Removing /tmp/foo"
  rm  -r /tmp/foo
}
trap cleanup EXIT
mkdir /tmp/foo
asdffdsa #Fails

ref: shellscript.sh ref: shellscript.sh

I don't know if it matters to you if it's before or after.我不知道这对你来说是之前还是之后。

You can set a script to run immediately after closing with "trap".您可以将脚本设置为在使用“陷阱”关闭后立即运行。 and then you can close the terminal.然后你可以关闭终端。

For Example;例如;

    trap  ./val.sh EXIT  #set command you want to run after close terminal 
    kill -9 $PPID        #kill current terminal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM