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
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
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.
if [ -f filename ]
will test for the existence of a regular file. There are other switches you can pass it to check for an executable or other attributes of a file.
Reference page for file testing
Once you run through all those pages,
Keep this Reference sheet handy.
Just to note that if you want something that works across all sh shells (not only bash) and cross-platform, the only way is:
ls filename >/dev/null 2>&1
if [ $? = 0 ]; then
echo "File exists"
fi