How to check a file exists
Solution 1
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.
Solution 2
http://tldp.org/LDP/abs/html/fto.html
Solution 3
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.
Solution 4
Reference page for file testing
Once you run through all those pages,
Keep this Reference sheet handy.
Related videos on Youtube
Simon Hodgson
Software Engineer, IT Manager, Sys Admin, Telecomms Engineer
Updated on September 17, 2022Comments
-
Simon Hodgson almost 2 years
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
-
Kevin Kuphal almost 15 yearsThis really belongs on stackoverflow
-
thepocketwade almost 15 yearsNot necessarily, this kind of thing is important in init scripts and other sysadmin tools. Thus, it shouldn't necessarily be migrated from either site to the other.
-
Benoit almost 15 yearsIf you're not even able to read a man page, you really should have a look at superuser.com
-
Kyle Brandt almost 15 yearsBenoit: The question is fine, I think, if you listen to podcast #58, they want questions like this. As a demo, Joel asked how to move the turtle in LOGO: stackoverflow.com/questions/1003841/…
-
Benoit almost 15 yearsKyle: As far as I understand, SF is for sys/admin related questions (even simple ones yes). But this questions is more about learning how to use an O/S, not about managing a server. That's why I think this question belongs to superuser.com
-
-
Sergey almost 15 yearsCheck it for folder with same name....
-
chris almost 15 yearsthis is bash / ksh only, not posix.
-
chris almost 15 yearsSingle brackets are an alias for test, which is a shell built-in. [[ ]] is a part of the extended bourne shell syntax of ksh and was adopted by bash.
-
chris almost 15 yearsYou can get rid of the $? nonsense. if ls filname > /dev/null ; then echo file exists ; fi
-
Johan almost 15 yearschange line 1 to #!/bin/bash, then you don't have to think about if it is ksh or bash.
-
chris almost 15 years@johan: Yes, and redirecting stderr of a compiler fixes all it's complaints.
-
cas almost 15 yearsthat works, but '-e' is the test for existence (regardless of what it is - file, symlink, device node, named pipe etc). '-f' tests whether it is a regular file. in bash, run 'help test' for a full list of such tests.