linux - Bash:我自己的退出过程

标签 linux bash

是否可以在我的 bash 脚本文件中定义我自己的退出函数。

例子:

$] vi myBash.sh

#!/usr/bash
function myFunc()
{
    echo "Inside myFunc"
}

function exit()
{
    echo "My Own Exit Called"
    exit 0
}

myFunc
exit 0

$] sh myBash.sh
Inside myFunc
My Own Exit Called

$]

最佳答案

为 EXIT (0) 设置陷阱:

trap exit_function_name EXIT

或者

trap 'exit command' EXIT

引用资料:

exit [n]

Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.

trap [-lp] [[arg] sigspec ...]

The command arg is to be read and executed when the shell receives signal(s) sigspec. If arg is absent (and there is a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to the shell). If arg is the null string the signal specified by each sigspec is ignored by the shell and by the commands it invokes. If arg is not present and -p has been supplied, then the trap commands associated with each sigspec are dis‐ played.

If a sigspec is EXIT (0) the command arg is executed on exit from the shell.

至于你的代码,可以这样写:

#!/bin/bash

function exit()
{
    echo "My Own Exit Called"
    # exit 0
}

trap exit EXIT

不要再调用 exit,因为它会触发陷阱并再次调用该函数。

更新

创建自定义函数时,使用builtin调用真正的exit:

function exit {
    echo "My Own Exit Called"   
    builtin exit 0  ## I think what you really wanted is builtin exit "$1"
}

这里有一个建议,因此您可以传递自己的退出消息和退出代码:

function exit {
    echo "$1"
    builtin exit "$2"
}

exit "My own exit called." 0

关于linux - Bash:我自己的退出过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24882354/

相关文章:

linux - 仅使用 bash 脚本陷阱提取文件 5 次

bash - sqoop创建impala Parquet 表

bash - Linux bash - 将文件分成两个单词

bash - 用新版本替换 bash 脚本会导致脚本的运行实例失败

linux - git pull 不应用 kubuntu/var/www/html 文件夹中的删除

linux - 如何使用 shell 脚本对文件对运行多个命令?

linux - 子目录未使用正确的组创建,即使父目录具有 SGID

linux - 如何使用 docker swarm 扩展具有多个暴露端口和多个卷的应用程序?

linux内核开发

linux - Bash 字符串日期错误值