一、nohup

nohup(no hang up)表示不挂起的意思,也就是当终端或者用户退出时,命令仍然运行,通常配合&一起使用,例如nohup xxx &。

二、command > file.out

把输出到控制台的日志重定向输出到file.out,需要注意的是错误信息不会输出到file.out中。
实验一下:

[root@develop chenzhenqing]# ls xxx
ls: cannot access xxx: No such file or directory
[root@develop chenzhenqing]# ls xxx > file.out
ls: cannot access xxx: No such file or directory
[root@develop chenzhenqing]# cat file.out 
[root@develop chenzhenqing]# 

上面的实验中,执行命令ls xxx > file.out,其中xxx是不存在的,查看file.out的内容,发现无内容。那么如果需要把错误日志也输出到file.out的话,则需要加上2>&1.

[root@develop chenzhenqing]# ls xxx > file.out 2>&1
[root@develop chenzhenqing]# cat file.out 
ls: cannot access xxx: No such file or directory
[root@develop chenzhenqing]# 

三、 2>&1

从上面实验例子中,如果想把控制台的错误信息也输出到文件中,则需要加上2>&1命令,在shell bash中,对应的说明如下:

  • 0:表示标准输入
  • 1:表示标准输出
  • 2:表示标准错误输出

而对于输出重定向到文件,只是重定向到标准输出,因此需要把标准错误输出(2)重定向到标准输出(1),也就是2>&1。需要说明一下的是1前面加上&表示标准输出1,如果不加上&则表示文件1,如下面例子。

[root@develop chenzhenqing]# ls xxx > file.out 2>1
[root@develop chenzhenqing]# cat file.out 
[root@develop chenzhenqing]# cat 1
ls: cannot access xxx: No such file or directory

四、最佳实践

1、对于需要把日志输出到指定文件的:
nohup xxx > out.log 2>&1 &
2、对于不需要把日志输出到指定文件的:
nohup xxx >/dev/null 2>&1 &

打赏
支付宝 微信
上一篇