I would do this in a loop:
for pathname in ~/file1 ~/file2; do
if [ -e "$pathname" ]; then
printf '"%s" exists\n' "$pathname"
else
printf '"%s" does not exist\n' "$pathname"
fi
done
This basically does the single test for existence for each pathname mentioned in the loop header, and decides what to output based on the result of the test. The output mentions the pathname examined and the result of the test.
If the pathnames matches a simple pattern, then this could be used in the loop:
for pathname in ~/file[12]; do ...; done
The question could also be interpreted like: Print each existing pathname, but if none of the files exists, print all pathnames and a note saying they don't exist.
set -- ~/file1 ~/file2
found=false
for pathname do
if [ -e "$pathname" ]; then
printf '"%s" exists\n' "$pathname"
found=true
fi
done
if ! "$found"; then
printf '"%s" does not exist\n' "$@"
fi
I'm using the list of positional parameters as a list here, holding the pathnames that we want to examine. I do this because we potentially want to loop over this list twice; once with our -e
tests, and then again (implicitly) in the call to printf
if no file was found to exist.
Using an array in bash
instead (requries a bit more typing):
files=( ~/file1 ~/file2 )
found=false
for pathname in "${files[@]}"; do
if [ -e "$pathname" ]; then
printf '"%s" exists\n' "$pathname"
found=true
fi
done
if ! "$found"; then
printf '"%s" does not exist\n' "${files[@]}"
fi
Note that files=( ~/file1 ~/file2 )
could also be written
files[0]=~/file1
files[1]=~/file2
Just a comment about the -f
test vs. the -e
test. The -e
test tests for existence, while the -f
test tests for existence and file type. If the pathname does not refer to a regular file (or a symbolic link to a regular file), then the -f
test may be false while the -e
test, at the same time, may be true. A "regular file" is a file that is not a directory, socket, named pipe or any of the other common Unix file types.
I opted for the -e
test rather than the -f
test in my answer since you were using the word "exists" repeatedly in the question, while not mentioning anything about file types.