I want to check for the existence of multiple directories, say, dir1
, dir2
and dir3
, in the working directory.
I have the following
if [ -d "$PWD/dir1" ] && [ -d "$PWD/dir2" ] && [ -d "$PWD/dir3" ]; then
echo True
else
echo False
fi
But I suspect there is a more elegant way of doing this. Do not assume that there is a pattern in the names of the directories.
The goal is to check for the existence of a few directories and for the nonexistence of others.
I'm using Bash, but portable code is preferred.
Best Answer
If you already expect them to be directories and are just checking whether they all exist, you could use the exit code from the
ls
utility to determine whether one or more "errors occurred":I redirect the output and stderr to
/dev/null
in order to make it disappear, since we only care about the exit code fromls
, not its output. Anything that's written to/dev/null
disappears — it is not written to your terminal.