linux中/dev/null与2>&1讲解

首先先来看下几种标识的含义:

  • /dev/null 表示空设备文件
  • 0 表示stdin标准输入
  • 1 表示stdout标准输出
  • 2 表示stderr标准错误

    先看/dev/null 

    command > /dev/null相当于执行了command 1 > /dev/null。执行command产生了标准输出stdout(用1表示),重定向到/dev/null的设备文件中

/dev/null可以理解为/dev路径下的空文件;该命令将command命令的标准输出输出到空文件中;

    再看 1>test.log

    执行./test.sh > res1.log 或 ./test.sh 1> res1.log结果为
我们发现stdout被重定向到了res1.log中,stderr并没有被重定向到res1.log中,stderr被打印到了屏幕上。
    2>test.log
    执行./test.sh 2> res3.log结果为
我们发现stderr被重定向到了res3.log中

    2>&1

    command>a 2>&1 可以理解为执行command产生的标准输出重定向到文件a中,标准错误也重定向到文件a中,期间只打开一次文件a,&1的含义就可以理解为用标准输出的引用,引用的就是重定向标准输出产生打开的a。
 
    执行./test.sh>res2.log 2>&1结果为
这次我们发现stdout和stderr都被重定向到了res2.log中了
 
下面是一个挂后台的样例:
 
nohup sh loop_dwa_m_sms_chunjie_fs_zdg.sh 20190120 >loop_dwa_m_sms_chunjie_fs_zdg.log 2>&1 &
 

原文地址:https://www.cnblogs.com/xiao02fang/p/10314921.html