4

I have a command that gives me a list of files, one on each line. Filenames are "normal" - no spaces, no need to escape parentheses etc.

Now I want to pipe that command to something like test -f and return true if and only if all of the files exist. (Behaviour with 0 lines can be undefined, I don't really care.)

So, something like

make_list_of_files | test -f

but actually working.

"Bashisms" are allowed, since I need it in Bash.

The files are not in the same directory, but they are in subdirectories of a current directory, and the paths have directory names in them, so for example

dir/file1
dir/file2
dir2/file3
  • 1
    <infile xargs ls -l >/dev/null 2>&1 – don_crissti Nov 12 '15 at 23:43
7
allExist(){
    while IFS= read -r f; do
      test -e "$f" || return 1
    done
}

make_list_of_files | allExist

This should work in all POSIX shells.

2

This becomes much easier using xargs, which returns a status code of 123 if any command returns a nonzero status:

if make_list_of_files | xargs ls &>/dev/null; then
    echo "All files exist";
else
    echo "here";
fi

This could be done as a one-liner in (ba)sh as well:

$ make_list_of_files | xargs ls &>/dev/null || echo "missing file"
$ make_list_of_files | xargs ls &>/dev/null && echo "all files present"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.