简体   繁体   English

shell脚本中是否有一种方法,如果[ <script exits with non-0 value> ] then; do <something>

[英]Is there a way in the shell script that if [ <script exits with non-0 value> ] then; do <something>

In the shell script, I want to do that if the shell script failed ( exited with non zero value), then before exiting the process, do something. 在shell脚本中,如果shell脚本失败(退出时返回非零值),我想这样做,然后在退出进程之前执行一些操作。

How could I insert such a if statement block in my shell script. 我如何在我的shell脚本中插入这样的if语句块。

Is that feasible? 那可行吗?

For example, 例如,

set -e
echo $password > confidential.txt
rm <file-that-does-not-exist>
rm confidential.txt

I want to make sure that the confidential.txt is made sure to be removed anyways 我想,以确保该confidential.txt作出肯定会被删除反正

Use the trap command: 使用trap命令:

trap 'if [ $? -ne 0 ]; then echo failed; fi' EXIT

The EXIT trap is run when the script exits, and $? EXIT脚本时将运行EXIT陷阱,并且$? contains the status of the last command before it exited. 包含最后一个命令退出前的状态。

Note that a shell script's exit status is the status of the last command that it executed. 请注意,shell脚本的退出状态是它执行的最后一个命令的状态。 So in your script, it will be the status of 所以在您的脚本中,它将是

rm confidential.txt

not the error from 不是来自的错误

rm filethatdoesnotexist

Unless you use set -e in the script, which makes it exit as soon as any command gets an error. 除非您在脚本中使用set -e ,否则它将在任何命令出错时立即退出。

Use trap with the EXIT pseudo signal: trapEXIT伪信号一起使用:

remove_secret () {
    rm -f /path/to/confidential.txt
}
trap remove_secret EXIT

You probably don't want the file to remain if the script exits with 0, so EXIT happens regardless of the exit code. 如果脚本以0退出,您可能不希望保留该文件,因此无论退出代码如何,都会发生EXIT

Note that without set -e , rm on a non-existent file doesn't stop the script. 请注意,如果没有set -e ,则不存在的文件上的rm不会停止脚本。

Assuming you're on Linux (or another operating system with /proc/*/fd ), you have an even better option: Delete confidential.txt before putting the password into it at all. 假设您使用的是Linux(或带有/proc/*/fd其他操作系统),则有一个更好的选择:完全删除密码后再删除confidential.txt

That can look something like the following: 看起来可能如下所示:

exec 3<>confidential.txt
rm -f -- confidential.txt
printf '%s\n' "$password" >&3

...and then, to read from that deleted file: ...然后从该已删除文件中读取:

cat "/proc/$$/fd/3"  ## where $$ is the PID of the shell that ran the exec command above

Because the file is already deleted , it's guaranteed to be eligible for garbage collection by your filesystem the moment your script (or the last program it started inheriting its file descriptors) exits or is killed, even if it's killed in a way that doesn't permit traps or signal processing to take place. 由于该文件已被删除 ,因此即使脚本(或它开始继承其文件描述符的最后一个程序)退出或被杀死,也可以保证文件系统有资格进行垃圾回收,即使该文件被杀死的方式不是允许进行陷阱或信号处理。

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

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