Bash脚本将在断开连接后继续存在,但不会中断用户 [英] Bash script that will survive disconnection, but not user break

查看:68
本文介绍了Bash脚本将在断开连接后继续存在,但不会中断用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个bash脚本,如果用户断开连接,它将继续运行,但是如果用户按Ctrl + C可以中止.

I want to write a bash script that will continue to run if the user is disconnected, but can be aborted if the user presses Ctrl+C.

我可以这样解决它的第一部分:

I can solve the first part of it like this:

#!/bin/bash
cmd='
#commands here, avoiding single quotes...
'
nohup bash -c "$cmd" &
tail -f nohup.out

但是按Ctrl + C显然会杀死tail进程,而不是主体.我可以两者都吃吗?也许使用屏幕?

But pressing Ctrl+C obviously just kills the tail process, not the main body. Can I have both? Maybe using Screen?

推荐答案

我想编写一个bash脚本,如果用户断开连接,它将继续运行,但是如果用户按下Ctrl键,则可以中止该脚本+ C.

I want to write a bash script that will continue to run if the user is disconnected, but can be aborted if the user presses Ctrl+C.

我认为这正是您提出的问题的答案,这个没有屏幕的问题:

I think this is exactly the answer on the question you formulated, this one without screen:

#!/bin/bash
cmd=`cat <<EOF
# commands here
EOF
`
nohup bash -c "$cmd" &

# store the process id of the nohup process in a variable
CHPID=$!        

# whenever ctrl-c is pressed, kill the nohup process before exiting
trap "kill -9 $CHPID" INT

tail -f nohup.out

但是请注意,nohup不可靠.当调用用户注销时,nohup也有可能立即退出.在这种情况下, disown 效果更好.

Note however that nohup is not reliable. When the invoking user logs out, chances are that nohup also quits immediately. In that case disown works better.

bash -c "$cmd" &
CHPID=$!
disown

这篇关于Bash脚本将在断开连接后继续存在,但不会中断用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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