Check whether files in a file list exist in a certain directory

The shell way, you'd write it:

comm -23 <(sort -u < "$1") <(ls -- "$2")

(assuming a shell with support for process substitution like ksh, zsh or bash)

comm is the command that reports the common lines between two sorted files. It displays is in 3 tab separated columns:

  1. lines only in the first file
  2. lines only in the second file
  3. lines common to both files

And you can pass -1, -2, and -3 options to remove the corresponding column.

So above, it will only report the first column: the lines that are in the file list, but not in the output of ls (ls does sort the file list by default, we assume file names in there don't contain newline characters).


The best way to iterate over the lines in a file is using the read builtin in a while loop. This is what you are looking for:

while IFS= read -r f; do
    if [[ -e $2/$f ]]; then
        printf '%s exists in %s\n' "$f" "$2"
    else
        printf '%s is missing in %s\n' "$f" "$2"
        exit 1
    fi
done < "$1"