开门见山,直接上货,干不干不知道,水是挺水的!!!
先上干干巴巴的
#第一种后台运行
#后台运行脚本
[root@localhost bin]# ./hello.sh >> hello2.out &
[1] 13076
#查看后台运行的脚本 jobs -l,jobs也行
[root@localhost bin]# jobs
[1]+ Running ./hello.sh >> hello2.out &
#后台任务调到前台执行
[root@localhost bin]# fg 1
./hello.sh >> hello2.out
#ctrl+z 暂停脚本执行
^Z
[1]+ Stopped ./hello.sh >> hello2.out
[root@localhost bin]# jobs -l
[1]+ 13076 Stopped ./hello.sh >> hello2.out
#将后台暂停的脚本继续执行
[root@localhost bin]# bg 1
[1]+ ./hello.sh >> hello2.out &
[root@localhost bin]# jobs -l
[1]+ 13076 Running ./hello.sh >> hello2.out &
#第二种后台运行
[root@localhost bin]# nohup ./hello.sh >hello1.out 2>&1 &
[2] 13803
[root@localhost bin]# jobs -l
[1]- 13076 Running ./hello.sh >> hello2.out &
[2]+ 13803 Running nohup ./hello.sh > hello1.out 2>&1 &
nohup加不加的区别,加了当前xshell页面断掉依旧运行,不加连接断了,脚本也不跑了。
水了吧唧的开始了
1、hello.sh脚本内容
#!/bin/bash
while true
do
echo "hello word"
sleep 1
done
2.jobs -l 显示后台执行的任务
3.bg 将后台暂停的任务继续在后台运行
4.fg 将前台运行的任务放到后台
5.ctrl+z 将前台运行的任务暂停
7.练习
./hello.sh & 将脚本放到后台执行但是会在前台显示结果,如下
fg 3 将后台运行的这个脚本放到前台运行,如下
上图虽然我是连续写的命令,但是一直在打印输出结果导致这种情况出现
ctrl+z 暂停此前台任务
7.后台启动任务
./hello.sh & 后台启动,但是会打印日志到前台
./hello.sh > hello.out & 后台启动,将日志打印到hello.out文件中去,但是用xshell中使用,xshell断掉的时候任务也会随之结束
./hello.sh >> hello2.out 2>&1 & 后台启动当xshell页面关闭后就后继续运行
测试
目前没有hello.sh进程在跑
开两个xshell页面,分别跑着两种后台命令
ps一下看下进程,此时有两个hello.sh的脚本在跑
再开两个xshell窗口分别tail hello1.ou和hello2.out的日志,看到都在打印日志
此时关闭./hello.sh > hello1.out & 运行的xshell窗口,发现hello1.out已经不再打印日志了,进程也少了一个
再关闭nohup ./hello.sh > hello2.out 2>&1 & 运行的shell窗口,hello2.out依旧在打印日志,ps看进程还在,但是jobs在新的shell窗口上看不到任何在后台执行的脚本
总结
nohup ./hello.sh > hello2.out 2>&1 & 就算当前xshell页面关掉了,后台脚本依旧在运行
./hello.sh > hello1.out & 当前xshell页面关掉了,后台脚本就不继续运行了。
在上述脚本中,问 > 和 >> 有啥区别?
还有jobs -l在别的页面看不到后台运行的脚本,为啥这个我是真不知道。