linux 关闭终端作业可以继续运行,如何运行将在终端关闭后继续运行的命令?

我有一个脚本可以:

在后台运行任意命令

阻止它们被终端窗口杀死

禁止输出

处理退出状态

我用它主要为gedit,evince,inkscape等所有有很多烦人的终端输出的。如果命令之前完成TIMEOUT,则返回nohup的退出状态,而不是零。

#!/bin/bash

TIMEOUT=0.1

#use nohup to run the command, suppressing its output and allowing the terminal to be closed

#also send nohup's output to /dev/null, supressing nohup.out

#run nohup in the background so this script doesn't block

nohup "${@}" >/dev/null 2>&1 &

NOHUP_PID=$!

#kill this script after a short time, exiting with success status - command is still running

#this is needed as there is no timeout argument for `wait` below

MY_PID=$$

trap "exit 0" SIGINT SIGTERM

sleep $TIMEOUT && kill $MY_PID 2>/dev/null & #ignore "No such process" error if this exits normally

#if the command finishes before the above timeout, everything may be just fine or there could have been an error

wait $NOHUP_PID

NOHUP_STATUS=$?

#print an error if there was any. most commonly, there was a typo in the command

[ $NOHUP_STATUS != 0 ] && echo "Error ${@}"

#return the exit status of nohup, whatever it was

exit $NOHUP_STATUS

例子...

>>> run true && echo success || echo fail

success

>>> run false && echo success || echo fail

Error false

fail

>>> run sleep 1000 && echo success || echo fail

success

>>> run notfound && echo success || echo fail

Error notfound

fail

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值