By Bill the Lizard


2009-03-12 14:48:43 8 Comments

I've used the following script to see if a file exists:

#!/bin/bash

FILE=$1     
if [ -f $FILE ]; then
   echo "File $FILE exists."
else
   echo "File $FILE does not exist."
fi

What's the correct syntax to use if I only want to check if the file does not exist?

#!/bin/bash

FILE=$1     
if [ $FILE does not exist ]; then
   echo "File $FILE does not exist."
fi

19 comments

@upteryx 2019-06-12 11:50:20

You can also group multiple commands in the one liner

[ -f "filename" ] || ( echo test1 && echo test2 && echo test3 )

or

[ -f "filename" ] || { echo test1 && echo test2 && echo test3 ;}

If filename doesn't exit, the output will be

test1
test2
test3

Note: ( ... ) runs in a subshell, { ... ;} runs in the same shell. The curly bracket notation works in bash only.

@Charles Duffy 2019-11-04 13:27:04

No, the curly bracket notation is not bash-only; it works in any POSIX-compliant shell.

@Mauro Zallocco 2019-08-27 19:45:47

If you want to use test instead of [], then you can use ! to get the negation:

if ! test "$FILE"; then
  echo "does not exist"
fi

@Stephane Chazelas 2016-10-14 15:18:33

In

[ -f "$file" ]

the [ command does a stat() (not lstat()) system call on the path stored in $file and returns true if that system call succeeds and the type of the file as returned by stat() is "regular".

So if [ -f "$file" ] returns true, you can tell the file does exist and is a regular file or a symlink eventually resolving to a regular file (or at least it was at the time of the stat()).

However if it returns false (or if [ ! -f "$file" ] or ! [ -f "$file" ] return true), there are many different possibilities:

  • the file doesn't exist
  • the file exists but is not a regular file (could be a device, fifo, directory, socket...)
  • the file exists but you don't have search permission to the parent directory
  • the file exists but that path to access it is too long
  • the file is a symlink to a regular file, but you don't have search permission to some of the directories involved in the resolution of the symlink.
  • ... any other reason why the stat() system call may fail.

In short, it should be:

if [ -f "$file" ]; then
  printf '"%s" is a path to a regular file or symlink to regular file\n' "$file"
elif [ -e "$file" ]; then
  printf '"%s" exists but is not a regular file\n' "$file"
elif [ -L "$file" ]; then
  printf '"%s" exists, is a symlink but I cannot tell if it eventually resolves to an actual file, regular or not\n' "$file"
else
  printf 'I cannot tell if "%s" exists, let alone whether it is a regular file or not\n' "$file"
fi

To know for sure that the file doesn't exist, we'd need the stat() system call to return with an error code of ENOENT (ENOTDIR tells us one of the path components is not a directory is another case where we can tell the file doesn't exist by that path). Unfortunately the [ command doesn't let us know that. It will return false whether the error code is ENOENT, EACCESS (permission denied), ENAMETOOLONG or anything else.

The [ -e "$file" ] test can also be done with ls -Ld -- "$file" > /dev/null. In that case, ls will tell you why the stat() failed, though the information can't easily be used programmatically:

$ file=/var/spool/cron/crontabs/root
$ if [ ! -e "$file" ]; then echo does not exist; fi
does not exist
$ if ! ls -Ld -- "$file" > /dev/null; then echo stat failed; fi
ls: cannot access '/var/spool/cron/crontabs/root': Permission denied
stat failed

At least ls tells me it's not because the file doesn't exist that it fails. It's because it can't tell whether the file exists or not. The [ command just ignored the problem.

With the zsh shell, you can query the error code with the $ERRNO special variable after the failing [ command, and decode that number using the $errnos special array in the zsh/system module:

zmodload zsh/system
ERRNO=0
if [ ! -f "$file" ]; then
  err=$ERRNO
  case $errnos[err] in
    ("") echo exists, not a regular file;;
    (ENOENT|ENOTDIR)
       if [ -L "$file" ]; then
         echo broken link
       else
         echo does not exist
       fi;;
    (*) syserror -p "can't tell: " "$err"
  esac
fi

(beware the $errnos support was broken with some versions of zsh when built with recent versions of gcc).

@Jahid 2015-04-28 19:40:16

You can do this:

[[ ! -f "$FILE" ]] && echo "File doesn't exist"

or

if [[ ! -f "$FILE" ]]; then
    echo "File doesn't exist"
fi

If you want to check for file and folder both, then use -e option instead of -f. -e returns true for regular files, directories, socket, character special files, block special files etc.

@Stephane Chazelas 2018-01-03 10:38:31

That is not bash-specific. The syntax comes from the Korn shell and is also available in zsh and bash. It has limited advantage over the standard [ utility here though.

@Stephane Chazelas 2018-01-03 10:42:36

regular files (as checked by -f) and directories are just two of many different types of files. There are also sockets, symlinks, devices, fifos, doors... [ -e will test for file existence (of any type including regular, fifo, directory...) after symlink resolution.

@Jahid 2018-01-03 15:59:32

@StephaneChazelas : I don't see any ksh or zsh tag anywhere. We are talking about bash or something that is standardized on most unix systems. So, within the context, it's bash specific. OP doesn't need to know of every whatever shells are out there :D

@Stephane Chazelas 2018-01-03 16:03:30

That was a comment on the "Bash specific" part of your answer.

@Jahid 2018-01-03 16:37:52

@StephaneChazelas : Yes, and within context (bash and the standard sh), it's bash specific. I don't see the point in your second comment, it's totally out of context. OP doesn't need -e, he needs -f.

@Mike S 2018-05-09 18:13:37

@Jahid, to call a general construct specific to only a certain utility is just wrong- because it's not Bash specific. If one can use it in ksh, then it's simply not contrained to this utility. The fact that it's being discussed under this topic is not license to say, "By the way, now that we're talking about Bash, let me introduce you to something that's specific to Bash." No- it's just not. -1 for being misleading in a technical forum. If you were writing about Python, would you say, "Now let me introduce you to this amazing Python-specific concept: The if statement." ? I don't think so.

@Mike S 2018-05-09 18:18:03

...You also miss the mark with your comment about -e. As Stephane says, -e returns true for almost any entity in the filesystem: fifos, directories, regular files, block special files, character special files, etc. Your answer appears to suggest that you're simply expanding a little bit on -f and adding directories to its match against regular files. You're not; it's much more broad than that.

@unbeknown 2009-03-12 14:50:57

You can negate an expression with "!":

#!/bin/bash
FILE=$1

if [ ! -f "$FILE" ]
then
    echo "File $FILE does not exist"
fi

The relevant man page is man test or, equivalently, man [ -- or help test or help [ for the built-in bash command.

@gniourf_gniourf 2013-06-29 10:05:54

In bash, [ is a builtin. So the relevant information is rather obtained by help [... but this shows that [ is a synonym for the test builtin, hence the relevant information is rather obtained by help test. See also the Bash Conditional Expression section in the manual.

@Keith Thompson 2013-09-21 19:04:48

@gniourf_gniourf: Yes, but the bash built-in [ command behaves very similarly to the external [ command, so either man test or man [ will give you a good idea of how it works.

@gniourf_gniourf 2013-09-21 21:54:56

@KeithThompson except that the bash builtin [ has more switches than the external command [ found on my system... Generally speaking I believe it's better to read the documentation specific to a given tool, and not the documentation specific to another vaguely related one. I might be wrong, though ;)

@André 2017-04-11 20:25:18

sometimes it may be handy to use && and || operators.

Like in (if you have command "test"):

test -b $FILE && echo File not there!

or

test -b $FILE || echo File there!

@SD. 2013-12-19 12:47:04

To test file existence, the parameter can be any one of the following:

-e: Returns true if file exists (regular file, directory, or symlink)
-f: Returns true if file exists and is a regular file
-d: Returns true if file exists and is a directory
-h: Returns true if file exists and is a symlink

All the tests below apply to regular files, directories, and symlinks:

-r: Returns true if file exists and is readable
-w: Returns true if file exists and is writable
-x: Returns true if file exists and is executable
-s: Returns true if file exists and has a size > 0

Example script:

#!/bin/bash
FILE=$1

if [ -f "$FILE" ]; then
   echo "File $FILE exists"
else
   echo "File $FILE does not exist"
fi

@user2350426 2015-08-05 18:10:39

There are three distinct ways to do this:

  1. Negate the exit status with bash (no other answer has said this):

    if ! [ -e "$file" ]; then
        echo "file does not exist"
    fi
    

    Or:

    ! [ -e "$file" ] && echo "file does not exist"
    
  2. Negate the test inside the test command [ (that is the way most answers before have presented):

    if [ ! -e "$file" ]; then
        echo "file does not exist"
    fi
    

    Or:

    [ ! -e "$file" ] && echo "file does not exist"
    
  3. Act on the result of the test being negative (|| instead of &&):

    Only:

    [ -e "$file" ] || echo "file does not exist"
    

    This looks silly (IMO), don't use it unless your code has to be portable to the Bourne shell (like the /bin/sh of Solaris 10 or earlier) that lacked the pipeline negation operator (!):

    if [ -e "$file" ]; then
        :
    else
        echo "file does not exist"
    fi
    

@Frozen Flame 2015-08-18 03:42:15

Any portability difference between ! [ and [ !?

@user2350426 2015-08-18 04:16:08

The ! [ is POSIX for shell pipelines 2.9.2 (any command) Otherwise, the exit status shall be the logical NOT of the exit status of the last command and [ ! is POSIX for test ! expression True if expression is false. False if expression is true. So, both are POSIX, and in my experience, both are extensively supported.

@Stephane Chazelas 2018-01-03 10:39:43

@FrozenFlame, the Bourne shell didn't have the ! keyword which was introduced by the Korn shell. Except maybe for Solaris 10 and older, you're unlikely to come across a Bourne shell these days though.

@BlueCacti 2014-01-16 14:25:58

Bash File Testing

-b filename - Block special file
-c filename - Special character file
-d directoryname - Check for directory Existence
-e filename - Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename - Check for regular file existence not a directory
-G filename - Check if file exists and is owned by effective group ID
-G filename set-group-id - True if file exists and is set-group-id
-k filename - Sticky bit
-L filename - Symbolic link
-O filename - True if file exists and is owned by the effective user id
-r filename - Check if file is a readable
-S filename - Check if file is socket
-s filename - Check if file is nonzero size
-u filename - Check if file set-user-id bit is set
-w filename - Check if file is writable
-x filename - Check if file is executable

How to use:

#!/bin/bash
file=./file
if [ -e "$file" ]; then
    echo "File exists"
else 
    echo "File does not exist"
fi 

A test expression can be negated by using the ! operator

#!/bin/bash
file=./file
if [ ! -e "$file" ]; then
    echo "File does not exist"
else 
    echo "File exists"
fi 

@BlueCacti 2014-05-05 10:59:13

@0x90 If you want, you are free to edit my post and add it to the list. I guess you mean: -n String - Check if the length of the string isn't zero. Or do you mean file1 -nt file2 - Check if file1 is newer then file 2 (you can also use -ot for older then)

@BlueCacti 2014-05-05 11:06:20

About -n: The unary operator -z tests for a null string, while -n or no operator at all returns True if a string is not empty. ~ ibm.com/developerworks/library/l-bash-test/index.html

@Mz A 2019-04-12 08:30:47

why didn't some add a function like function exists() { ⏎ if [ -e "$1" ]; then echo "$1 exists" else echo "$1 does not exist" fi }

@Simmant 2013-08-29 06:59:47

This shell script also works for finding a file in a directory:

echo "enter file"

read -r a

if [ -s /home/trainee02/"$a" ]
then
    echo "yes. file is there."
else
    echo "sorry. file is not there."
fi

@Jonathan Leffler 2015-08-05 21:01:12

It isn't clear that this adds anything that other answers have not already given. It hard-codes a pathname. Since the question is tagged bash, it could use read -p "Enter file name: " -r a to prompt as well as read. It does use quotes around the variable; that's good, but should be explained. It might be better if it echoed the file name. And this checks that the file exists and is not empty (that's the meaning of -s) whereas the question asks about any file, empty or not (for which -f is more appropriate).

@lancerex 2014-05-21 06:11:22

The simplest way

FILE=$1
[ ! -e "${FILE}" ] && echo "does not exist" || echo "exists"

@Lemon Kazi 2015-07-03 08:39:37

This code also working .

#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
 echo "File '$FILE' Exists"
else
 echo "The File '$FILE' Does Not Exist"
fi

@artdanil 2012-01-24 19:43:47

You should be careful about running test for an unquoted variable, because it might produce unexpected results:

$ [ -f ]
$ echo $?
0
$ [ -f "" ]
$ echo $?
1

The recommendation is usually to have the tested variable surrounded by double quotation marks:

#!/bin/sh
FILE=$1

if [ ! -f "$FILE" ]
then
   echo "File $FILE does not exist."
fi

@Uwe 2013-05-28 11:43:32

The recommendation is to have every variable surrounded by double quotation marks, unless you know exactly that you have one of the rare cases where it's unnecessary, or one of the even rarer cases where it's harmful. (And no, this is not one of them.)

@artdanil 2013-05-28 23:29:21

Would you care to elaborate why this is not the case to use double quotation mark? Otherwise I don't see the usefulness in the comment.

@Uwe 2013-05-29 09:03:59

I meant: This is not one of the rare cases where it's unnecessary or harmful. A shell programmer should get used to enclose (almost) every variable in double quotes; this rule is not limited to [ ... ].

@tripleee 2016-05-27 16:37:35

@J. M. Becker 2011-10-18 16:09:23

I prefer to do the following one-liner, in POSIX shell compatible format:

$ [ -f "/$DIR/$FILE" ] || echo "$FILE NOT FOUND"

$ [ -f "/$DIR/$FILE" ] && echo "$FILE FOUND"

For a couple of commands, like I would do in a script:

$  [ -f "/$DIR/$FILE" ] || { echo "$FILE NOT FOUND" ; exit 1 ;}

Once I started doing this, I rarely use the fully typed syntax anymore!!

@PointedEars 2012-11-09 02:59:48

First of all, unquoted variable references are error-prone. That said, where does it say in any bash manpage that the [ or test built-in would test for file existence of the argument by default (as opposed to -e)? Would that not be ambiguous? AFAIK (and AIUI the section "CONDITIONAL EXPRESSIONS") the only thing that is tested with your approach is that the argument is not empty (or undefined), which is, in this case, a tautology (let $DIR = '' and $FILE = '', then the argument is still '//').

@PointedEars 2012-11-09 03:05:42

Proof: ls /foo, result ls: cannot access /foo: No such file or directory. [ /foo ] && echo 42, result 42. GNU bash, version 4.2.37(1)-release (i486-pc-linux-gnu).

@J. M. Becker 2012-11-17 23:42:11

@PointedEars: I failed to specify the -f option, at the moment I wrote this answer. Obviously you could always use -e, if your not sure it will be a regular file. Additionally In all my scripts I quote these constructs, I must have just submitted this without adequate proofing.

@PointedEars 2012-11-18 01:33:22

ACK. But you probably know that a one-liner cannot solve the if-else problem: [ $condition ] && if_true || if_false is error-prone. In any event, I find [ ! -f "$file" ] && if_not_exists easier to read and understand than [ -f "$file" ] || if_not_exists.

@Elazar Leibovich 2011-08-11 09:15:51

It's worth mentioning that if you need to execute a single command you can abbreviate

if [ ! -f "$file" ]; then
    echo "$file"
fi

to

test -f "$file" || echo "$file"

or

[ -f "$file" ] || echo "$file"

@Jonathan 2017-03-25 10:43:06

Thanks! Needed an alternative that does not use [[ ]]

@guns 2009-03-12 14:52:16

[[ -f $FILE ]] || printf '%s does not exist!\n' "$FILE"

Also, it's possible that the file is a broken symbolic link, or a non-regular file, like e.g. a socket, device or fifo. For example, to add a check for broken symlinks:

if [[ ! -f $FILE ]]; then
    if [[ -L $FILE ]]; then
        printf '%s is a broken symlink!\n' "$FILE"
    else
        printf '%s does not exist!\n' "$FILE"
    fi
fi

@Dimitrios Mistriotis 2011-04-20 08:35:36

May I ask why the two "["s in the test? (eg [[ ! -a $FILE ]]). I tried all the options mentioned on a solaris box and only that one worked, so grateful, but why?

@bw1024 2012-02-14 23:40:13

Double brackets are a "modern" extension; eg they won't do word splitting (such as for filenames with spaces) and still work for empty strings: mywiki.wooledge.org/BashFAQ/031

@Luca Borrione 2012-09-01 20:55:27

according to tldp.org/LDP/abs/html/fto.html -a is identical in effect to -e. It has been "deprecated," and its use is discouraged. Anyhow +1 for mentioning to check on broken symlink too

@Good Person 2012-10-26 15:41:08

@dimitrismistriotis two "[" is a non-portable extension implemented (differently) by zsh & bash; generally you should avoid it if at all possible.

@Steve Powell 2014-01-17 16:04:33

See SO 321348 for a good reason why -a can't be negated in single bracket conditional expressions. Avoid -a altogether, I suggest.

@Michael Potter 2014-07-10 16:02:32

I up voted this BECAUSE it used [[. It is a widely used extension. If you know you are using bash then there is no reason to not use it. It is much less error prone than [.

@ormaaj 2014-09-14 01:58:28

Changed this around a bit to eliminate -a, but also because -a is equivalent to -e, which returns true for an existing file regardless of type, you'd run into trouble if adding checks for fifos or sockets in the second example.

@John Feminella 2009-03-12 14:50:01

The test command ([ here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:

if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

@DavidWinterbottom 2010-09-29 12:09:41

More succinctly: [ ! -f /tmp/foo.txt ] && echo "File not found!"

@mivk 2012-02-02 15:41:47

I struggled a bit to find the right syntax for "if any of 2 files does not exist". The following both work: if [ ! \( -f "f1" -a -f "f2" \) ] ; then echo MISSING; fi if [ ! -f "f1" ] || [ ! -f "f2" ] ; then echo MISSING; fi

@David W. 2013-06-26 21:08:43

@DavidWinterbottom Even more succulently: [ -f /tmp/foo.txt ] || echo "File not found!"

@SD. 2013-12-19 13:41:15

Parameter can be any one of the following: -e: Returns true value, if file exists -f: Return true value, if file exists and regular file -r: Return true value, if file exists and is readable -w: Return true value, if file exists and is writable -x: Return true value, if file exists and is executable -d: Return true value, if exists and is a directory

@BlueCacti 2014-01-25 20:44:13

If you want to use 2 conditions in an if-operation, use the -a operator, this means AND. I think this is also possible with & if you use the [[ ]] operator

@Acumenus 2015-08-01 02:16:08

There is an asymmetry in using ! -f with && versus using -f with ||. This has to do with the exit code returned by the non/existence check. If you need your line to always exit cleanly with exit code 0 (and sometimes you don't want this constraint), the two approaches are not interchangeable. Alternatively, just use an if statement and you no longer have to worry about the exit code of your non/existence check.

@MariusP 2015-08-27 14:25:52

if the file name is dynamic, test it with if [ ! -f "$filename" ]; then... because it might contain spaces

@David Mann 2015-10-23 20:41:47

Used this to only run a cron job if the script exists, since our cron tasks deploy out before our app code base * * * * * [ -f foo.php] && php foo.php

@Rany Albeg Wein 2016-01-16 14:08:52

[[ is a bash keyword similar to (but more powerful than) the [ command. See <mywiki.wooledge.org/BashFAQ/031> and <mywiki.wooledge.org/BashGuide/TestsAndConditionals>. Unless you're writing for POSIX sh, it is recommend to use [[.

@Ghilas BELHADJ 2016-06-02 14:25:46

Keep a space between [ and !, it will not work otherwise

@Léo Léopold Hertz 준영 2016-10-29 10:47:12

I propose [[ ! -f ... ]]; then. Why you are not using double brackets? - - I cannot get your proposal work.

@android developer 2013-03-31 13:22:58

The test thing may count too. It worked for me (based on Bash Shell: Check File Exists or Not):

test -e FILENAME && echo "File exists" || echo "File doesn't exist"

@user2350426 2013-05-04 22:29:20

To reverse a test, use "!". That is equivalent to the "not" logical operator in other languages. Try this:

if [ ! -f /tmp/foo.txt ];
then
    echo "File not found!"
fi

Or written in a slightly different way:

if [ ! -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or you could use:

if ! [ -f /tmp/foo.txt ]
    then echo "File not found!"
fi

Or, presing all together:

if ! [ -f /tmp/foo.txt ]; then echo "File not found!"; fi

Which may be written (using then "and" operator: &&) as:

[ ! -f /tmp/foo.txt ] && echo "File not found!"

Which looks shorter like this:

[ -f /tmp/foo.txt ] || echo "File not found!"

Related Questions

Sponsored Content

24 Answered Questions

[SOLVED] How to check if a string contains a substring in Bash

  • 2008-10-23 12:37:31
  • davidsheldon
  • 1978985 View
  • 2459 Score
  • 24 Answer
  • Tags:   string bash substring

33 Answered Questions

[SOLVED] How do I parse command line arguments in Bash?

10 Answered Questions

[SOLVED] Check existence of input argument in a Bash shell script

  • 2011-06-26 05:49:21
  • user775187
  • 1181445 View
  • 1282 Score
  • 10 Answer
  • Tags:   bash shell

16 Answered Questions

[SOLVED] In the shell, what does " 2>&1 " mean?

  • 2009-05-03 22:57:00
  • Tristan Havelick
  • 1063877 View
  • 2191 Score
  • 16 Answer
  • Tags:   bash shell unix redirect

35 Answered Questions

[SOLVED] How can I check if a program exists from a Bash script?

  • 2009-02-26 21:52:49
  • gregh
  • 647210 View
  • 2109 Score
  • 35 Answer
  • Tags:   bash

32 Answered Questions

[SOLVED] How do I split a string on a delimiter in Bash?

21 Answered Questions

[SOLVED] How can I declare and use Boolean variables in a shell script?

30 Answered Questions

[SOLVED] How to concatenate string variables in Bash

43 Answered Questions

[SOLVED] How to count all the lines of code in a directory recursively?

  • 2009-08-31 17:42:20
  • user77413
  • 756286 View
  • 1575 Score
  • 43 Answer
  • Tags:   bash shell

14 Answered Questions

[SOLVED] How to mkdir only if a dir does not already exist?

Sponsored Content