Checking existence of files and directories on UNIX using shell scripting

Having had a UNIX shell script attempt to copy a non-existent file, I decided to take another look for ways to test the existence of a file. For directory existence checking, I was testing for the return code from the cd command and I suppose that the ls command might help for files. However, I did find a better way:

if [ -f $filename ]

then

echo "This filename [$filename] exists"

elif [ -d $dirname ]

then

echo "This dirname [$dirname] exists"

else

echo "Neither [$dirname] or [$filename] exist"

fi

The -d and -f flags within the evaluation expressions test for existence of directories and files, respectively. One gotcha is that those spaces within the brackets are important too but it is a very way of doing what I wanted.

One comment

  1. [...] I shared a way to test for directory (-d operator) and file (-f operator) existence that follows the above coding convention. However, there are a plethora of others and I have made a [...]

  • As is commonly the case with places like these, all the views that you find expressed on here in postings and articles are mine alone and not those of any organisation with which I have any association, through work or otherwise. With regards to any comments left on the site, I reserve the right to reject any that are inappropriate. Otherwise, whatever is said is the sole responsibility of whoever is leaving the comment.