3

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
chris
  • 11,784
  • 6
  • 41
  • 51
Simon Hodgson
  • 681
  • 3
  • 8
  • 15
  • This really belongs on stackoverflow – Kevin Kuphal Aug 05 '09 at 13:52
  • 4
    Not 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. – thepocketwade Aug 05 '09 at 13:54
  • If you're not even able to read a man page, you really should have a look at superuser.com – Benoit Aug 05 '09 at 13:59
  • 2
    Benoit: 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: http://stackoverflow.com/questions/1003841/how-do-i-move-the-turtle-in-logo/1003856#1003856 – Kyle Brandt Aug 05 '09 at 14:03
  • Kyle: 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 – Benoit Aug 05 '09 at 15:47

6 Answers6

9

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.

Kyle Brandt
  • 82,107
  • 71
  • 302
  • 444
8

http://tldp.org/LDP/abs/html/fto.html

piotrsz
  • 216
  • 1
  • 2
4

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.

thepocketwade
  • 1,525
  • 5
  • 16
  • 27
  • that 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. – cas Aug 05 '09 at 21:54
1

Reference page for file testing

Once you run through all those pages,
Keep this Reference sheet handy.

nik
  • 7,040
  • 2
  • 24
  • 30
0

There is always the man pages:

man test

Chad Huneycutt
  • 2,096
  • 1
  • 16
  • 14
0

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
sucuri
  • 2,817
  • 1
  • 22
  • 22