"ls -t . | while read line" 是什么意思?

What does "ls -t . | while read line" mean?

代码如下:

if test $# -eq 1
then
  if test  = "--exec"
  then
    ls -t . | while read line
    do
      if test -f $line -a -x $line
      then
        echo $line
      fi
    done
  fi
fi

我不明白.ls -t . | while read line这里的用处;你能解释一下吗?

该行按照修改时间升序列出了当前目录下的所有文件。管道运算符将目录列表的结果发送到 while 循环,while 循环将 ls 命令的每一行读入变量 "line"。当我做这种事情时,我通常使用 foreach 循环,但无论哪种方式都有效。

您的代码只是打印出当前文件夹中的所有可执行文件,按修改时间排序。

通常 shell 编写脚本非常危险,因为您可能在没有真正意识到的情况下编写出非常容易出错或风格不佳的代码。或者即使你做了,你也可能对问题没有正确的认识。

为了实现相同的目标,我会写下以下内容:

find . -maxdepth 1 -type f -executable -printf '%T@ %p[=10=]' | sort -zk 1nr | sed -z 's/^[^ ]* //'

它非常简洁,没有错误的余地。