Linux – How to check a file exists

linuxunix-shell

How do I determine that a file exists using a shell script?

I.e:

#!/bin/sh

if [ Does File Exist? ]
then
    do this thing
fi

Best Answer

You probably want /bin/bash unless you need to use /bin/sh, /bin/sh is more restricted. So if you are using bash:

Like so:

 if [[ -e filename ]]; then
    echo 'exists'
 fi

If your filename is in a variable, then use the following, the double quotes are important if the file has a space in it:

if [[ -e "$myFile" ]]; then
   echo 'exists'
fi

If you are using sh, and want to be compatible with the IEEE Std 1003.1,2004 Edition, then use single brackets instead. The -e switch is still supported.