Search code examples
linuxbashfileoutputls

Bash write ls error to file


I have a folder with lots of files named with a continuing number and some text, but some numbers are missing. I want to write all missing numbers into a file.

Here is what I got so far:

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

The output looks like that:

all existing files are written into file, all errors into console. I want exactly the other way. All errors (ls: ..file not found) written into the file!

I tried to use the complete command ls $files* | grep -v 'kasse*', but then I only get a file with empty lines.

Thanks for your help!


Solution

  • 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