linux shell中经常会使用后台运行某个脚本

那么,下面的几种区别在哪呢

commandcommand > /dev/nullcommand > /dev/null 2>&1command &command &> /dev/nullnohup command &> /dev/null

下面分别简单地谈一下

# 以test.sh为例[root@localhost ~]# cat test.sh #!/bin/bash#while [  ‘1’ == ‘1’ ] ;do
	echo `date "+%Y-%m-%d %H:%M:%S"` 
	sleep 100done
command

直接执行,命令输出会显示在终端界面上,ctrl-C会终止命令的运行

[root@localhost ~]# bash test.sh 2016-08-07 20:49:47^C
[root@localhost ~]#
command > /dev/null

直接执行,命令标准输出会定向到null设备,即忽略标准输出1,但错误输出2会显示, 其实这等同于command 1 > /dev/null

[root@localhost ~]# cat test.sh#!/bin/bash#while [  ‘1’ == ‘1’ ] ;do
	echo `date "+%Y-%m-%d %H:%M:%S"` 
	ll
	sleep 100done[root@localhost ~]# bash test.sh > /dev/nulltest.sh: line 5: ll: command not found
^C
command > /dev/null 2>&1

这里首先和上面命令一样会把1输出到null设备,2重定向到1,那么2也会导null设备, 所以所有输出均送到了null设备

command &

这个想必大家都用过,后台执行,然而当我们退出终端后,command就会终止 这是因为我们的终端相当于一个父进程 ,一旦父进程退出,就会给其所有子进程发送hangup信号,子进程收到就会退出。 这里我不再举例子 如果我们在头加上nohup,也就是使用nohup command &,那么父进程就不会发送hangup给这个子进程,从而会一直在后台运行

command &> /dev/null 和 command > /dev/null 2>&1区别

网上并没有说多大区别,这是谈到ksh对于后者兼容更好,也就是满足了需求,所以推荐后者,当然如果确定当前平台,使用前者似乎更方便少,打了4个字符

后台控制
# 后台的命令可以通过jobs查看[root@localhost ~]# jobs[1]-  Running                 bash test.sh &
[2]+  Running                 bash test1.sh &# 调到前后台可以通过bg %JOB_NUMBER fg %JOB_NUMBER来完成,比如把job 1调到前台[root@localhost ~]# fg %1bash test.sh# 命令行就会一直持续这样,ctrl-Z可以让其停止运行在后台[root@localhost ~]# fg %1bash test.sh
^Z
[1]+  Stopped                 bash test.sh# 如何让其后台运行,因为现在状态为stopped,bg %1,你会发现bg 1也行[root@localhost ~]# bg 1[1]+ bash test.sh &
[root@localhost ~]# jobs[1]-  Running                 bash test.sh &
[2]+  Running                 bash test1.sh &