使用陷阱在ZSH中退出shell脚本的正确方法? [英] Proper way to use a trap to exit a shell-script in ZSH?

查看:107
本文介绍了使用陷阱在ZSH中退出shell脚本的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在不退出Shell的情况下使Zshell脚本中的trap函数正常工作.我有一个简单的倒数计时器,希望能够使用^ C进行中断,并且当我这样做时,我希望陷阱更改终端中的光标状态.

I'm having trouble getting a trap function in a Zshell-script to work without exiting the shell. I have a simple countdown timer that I want to be able to interrupt using ^C, and when I do I want the trap to change the cursor status in the terminal.

我的语法是:

#!/bin/zsh

#!/bin/zsh

trap 'tput cnorm; exit' INT TERM

我也尝试过:

trap 'tput cnorm; kill -9 $$' INT TERM

两个中断都完全退出外壳.如何仅退出脚本并返回命令行?

Both interrupts exit the shell entirely. How do I only exit the script and return to the command line?

任何指导将不胜感激!

推荐答案

使用陷阱处理信号

TRAPINT() {
    echo "TRAPINT() called: ^C was pressed"
}

TRAPQUIT() {
    echo "TRAPQUIT() called: ^\\ was pressed"
}

TRAPTERM() {
    echo "TRAPTERM() called: a 'kill' command was aimed at this program's process ID"
}

TRAPEXIT() {
    echo "TRAPEXIT() called: happens at the end of the script no matter what"
}

for i in {1..9}; do
    echo ${i}
    sleep 1
done

对于所有这些 TRAP [NAL]()函数,如果最终命令为 return 0 (或者如果根本没有return语句,则执行代码)如果该函数的返回状态为非零,则将继续该程序从中断处继续执行,就好像该信号已被接受,捕获和处理一样.则陷阱的返回状态将保留,并且先前执行的命令执行位置将被中断.您可以执行 return $((128 + $ 1))返回与未捕获信号相同的状态

For all of these TRAP[NAL]() functions, if the final command is return 0 (or if there is no return statement at all, then code execution will continue where the program left off, as if the signal was accepted, caught, and handled. If the return status of this function is non-zero, then the return status of the trap is retained, and the command execution that was previously taking place will be interrupted. You can do return $((128+$1)) to return the same status as if the signal had not been trapped

关于您的shell被杀死的原因,是因为调用 kill -9 $$ 会将信号9发送到与您的shell关联的进程ID.信号#9或 SIGKILL 是陷阱无法处理的一个信号.如果某个程序确实真正需要立即停止且不允许清理,那是一种万不得已的杀戮".

As to why your shell is getting killed, it's because calling kill -9 $$ will send the the signal 9 to the process ID associated with your shell. Signal #9, or SIGKILL is the one signal that can't be handled with traps. It's sort of a "kill of last resort" if a program truly needs to stop immediately, with no cleanup permitted.

这篇关于使用陷阱在ZSH中退出shell脚本的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆