gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:37 24 4
gpt4 key购买 nike

是否可以在我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com