Bash将ls错误写入文件

时间:2016-05-06 21:08:50

标签: linux bash file output ls

我有一个文件夹,其中包含许多以连续编号和一些文字命名的文件,但缺少一些数字。我想将所有缺失的数字写入文件。

这是我到目前为止所得到的:

#!/bin/bash
for (( c=23457; c<=24913; c++ ))
do
  files=$(printf %q kassensystem/documents/"${c}")
  ret=$(ls $files*)
  echo "$ret" >> ./out.log
done

输出如下:

将所有现有文件写入文件,将所有错误写入控制台。我完全想要另一种方式。写入文件的所有错误(ls: ..file not found)!

我尝试使用完整的命令ls $files* | grep -v 'kasse*',但后来我只得到一个空行的文件。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

exec 4>out.log  # open output file just once, not once per write

for (( c=23457; c<=24913; c++ )); do
  files=( kassensystem/documents/"$c"* ) # glob into an array
  [[ -e $files ]] || echo "$c" >&4       # log if first file in array doesn't exist
done

答案 1 :(得分:1)

仅使用stderr重定向exec,让stdout显示在终端上:

#!/bin/bash

# redirect stderr to a file
exec 2> out.log

shopt -s failglob
for (( c=23457; c<=24913; c++ ))
do
   echo "kassensystem/documents/$c"*
done
如果匹配的文件不存在,

shopt -s failglob将写入stderr。