`if ls /etc/*release 1>/dev/null 2>&1` 是如何工作的?请解释

How does: `if ls /etc/*release 1>/dev/null 2>&1` work? An explanation please

有人可以帮助我理解代码中包含的条件 ls /etc/*release 1>/dev/null 2>&1

    if ls /etc/*release 1>/dev/null 2>&1; then
       echo "<h2>System release info</h2>"
       echo "<pre>"
       for i in /etc/*release; do

           # Since we can't be sure of the
           # length of the file, only
           # display the first line.

           head -n 1 $i
       done
       uname -orp
       echo "</pre>"
    fi

我几乎不理解那一行,但我特别想知道的是:

  1. 为什么它不必使用 'test' 语法,即 [ expression ]
  2. 条件中的空格也很迷惑,1>/dev/nullls语句中的变量吗?
  3. 什么是 2>&1

我理解此声明的目的,即;如果 /etc/ 目录下存在名称为 release 的文件,语句将继续,我只是不明白这是如何实现的。

谢谢你的帮助

[ 不是特殊字符,它是一个命令(/bin/[/usr/bin/[,通常是 link 到 test)。也就是说

if [ ...
if test ...

是一样的。为此,test 忽略 ] 作为最后一个参数,如果它被称为 [.

if 只是响应它调用的命令的退出代码。退出代码 0 表示成功或 "true".

1>/dev/null 2>&1 将 stdout (1) 重定向到设备 /dev/null 然后将 stderr (2) 重定向到 stdout 这意味着该命令无法显示和输出或终端错误。

由于 stdout 不是普通文件或设备,您必须使用 >& 进行重定向。

乍一看,人们会认为 if [ -e /etc/*release ] 是更好的解决方案,但 test -e 不适用于模式。

test 程序只是评估它的参数,return 代码 0 或 1 来判断它是否正确。

但是您可以将任何 shell commands/function 与 if 一起使用。如果 return 代码 ($?) 为 0,它将执行 then 部分。 因此,在这里,我们查看 ls return 0(文件匹配)。

所以,最后,相当于写if [ -e /etc/*release ] ; then,多了"shell-liked"。

最后两个语句 1>/dev/null2>&1 只是为了避免显示 ls

的输出
  • 1>/dev/null 将标准输出重定向到 /dev/null,因此不会显示标准输出
  • 2>&1 将 stderr 重定向到 stdout。这里,stdout 被重定向到 /dev/null,所以所有内容都被重定向到 /dev/null