如何让shell脚本在后台执行
背景
在项目得实际情况中,可能要执行很多得脚本。一个shell可能执行要1个小时,如果一个执行完在执行另外得,这是不合理得。针对这种情况,Linux给出了nohup,这个完美得解决了这一问题。
Linux之nohup命令
nohup 命令
nohup 命令用于不挂断地运行命令 ,一般和 & 一起使用
命令格式:nohup command &
文件描述符
Linux 系统预留三个文件描述符:0、1 和 2,如下所示:
0——标准输入(stdin)
1——标准输出(stdout)
2——标准错误(stderr)
实际演练
执行nohup_1.sh,把输出ID和时间循环打印进日志
#!/bin/bash
# watch -n 10 'date >> /file/log/date.txt'
for((i=1;i<101;i++));do
# echo $i
sleep 10
date >> /file/log/date.txt
echo "The value is: $i" >> /file/log/date.txt
使用nohup命令执行nohup_1.sh
nohup ./nohup_1.sh > /file/log/nohup.log 2>&1 &
查看nohup_1.sh执行进程
ps -ef | grep nohup_1
# 或者
ps -aux | grep nohup_1
# 或者
ps -def | grep nohup_1
查看执行日志
[root@dongjj-2004 log]# cat date.txt
2022年 04月 12日 星期二 12:56:07 CST
The value is: 1
2022年 04月 12日 星期二 12:56:17 CST
[root@dongjj-2004 log]# cat nohup.log
nohup: 忽略输入
终止执行shell
[root@dongjj-2004 shell]# kill 2891
[root@dongjj-2004 shell]# ps -ef | grep nohup_1.sh
root 2999 1987 0 12:59 pts/0 00:00:00 grep --color=auto nohup_1.sh
[1]+ 已终止 nohup ./nohup_1.sh > /file/log/nohup.log 2>&1