Linux / UNIX: Find Out If File Exists With Conditional Expressions in a Bash Shell

Posted on in Categories Howto, Linux, RedHat/Fedora Linux, Shell scripting, UNIX last updated May 2, 2017

With the help of BASH shell and IF command, it is possible to find out if a file exists or not on the filesystem. A conditional expression (also know as “evaluating expressions”) can be used by [[ compound command and the test ([) builtin commands to test file attributes and perform string and arithmetic comparisons.

Find if a regular file does not exist in Bash
You can easily find out if a regular file does or does not exist in Bash shell under macOS, Linux, FreeBSD, and Unix-like operating system. You can use [ expression ], [[ expression ]], test expression, or if [ expression ]; then .... fi in bash shell along with a !operator. Let us see various ways to find out if a file exists or not in bash shell.

Syntax

The general syntax is as follows:
[ parameter FILE ]
OR
test parameter FILE
OR
[[ parameter FILE ]]
Where 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.

Please note that the [[ works only in Bash, Zsh and the Korn shell, and is more powerful; [ and test are available in POSIX shells. Let us see some examples.

Find out if file /etc/passwd file exist or not

Type the following commands:
$ [ -f /etc/passwd ] && echo "File exist" || echo "File does not exist"
$ [ -f /tmp/fileonetwo ] && echo "File exist" || echo "File does not exist"

How can I tell if a regular file named /etc/foo does not exist in Bash?

You can use ! operator as follows:
[ ! -f /etc/foo ] && echo "File does not exist"Exists
OR

#!/bin/bash
file="/.config/backup.cfg"
if [ ! -f "$file" ]
then
    echo "$0: File '${file}' not found."
fi

[[ example

Type the following commands:
$ [[ -f /etc/passwd ]] && echo "File exist" || echo "File does not exist"
$ [[ -f /tmp/fileonetwo ]] && echo "File exist" || echo "File does not exist"

Find out if directory /var/logs exist or not

Type the following commands:
$ [ -d /var/logs ] && echo "Directory exist" || echo "Directory does not exist"
$ [ -d /dumper/fack ] && echo "Directory exist" || echo "Directory does not exist"

[[ example

$ [[ -d /var/logs ]] && echo "Directory exist" || echo "Directory does not exist"
$ [[ -d /dumper/fake ]] && echo "Directory exist" || echo "Directory does not exist"

Are two files are the same?

Use the -ef primitive with the [[ new test command:

## first compare /etc/resolv.conf with /etc/resolv.conf ##
[[ /etc/resolv.conf -ef /etc/resolv.conf ]] && echo "Same files" || echo "Noop"
 
## now compare /etc/resolv.conf with /etc/passwd ##
[[ /etc/resolv.conf -ef /etc/passwd ]] && echo "Same files" || echo "Noop"

Shell script example

You can use conditional expressions in a shell script:

#!/bin/bash
FILE="$1"
 
if [ -f "$FILE" ];
then
   echo "File $FILE exist."
else
   echo "File $FILE does not exist" >&2
fi

Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf

You can use this technique to verify that backup directory or backup source directory exits or not in shell scripts. See example script for more information.

A complete list for file testing in bash shell

From the test command man page:

[ Expression ]Meaning
-b filename Return true if filename is a block special file.
-c filename Return true if filename exists and is a character special file.
-d filename Return true filename exists and is a directory.
-e filename Return true filename exists (regardless of type).
-f filename Return true filename exists and is a regular file.
-g filename Return true filename exists and its set group ID flag is set.
-h filename Return true filename exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead.
-k filename Return true filename exists and its sticky bit is set.
-n filename Return true the length of string is nonzero.
-p filename Return true filename is a named pipe (FIFO).
-r filename Return truefilename exists and is readable.
-s filename Return true filename exists and has a size greater than zero.
-t file_descriptor Return true the filename whose file descriptor number is file_descriptor is open and is associated with a terminal.
-u filename Return true filename exists and its set user ID flag is set.
-w filename Return true filename exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true.
-x filename Return true filename exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched.
-z string Return true the length of string is zero.
-L filename Return true filename exists and is a symbolic link.
-O filename Return true filename exists and its owner matches the effective user id of this process.
-G filename Return true filename exists and its group matches the effective group id of this process.
-S filename Return true filename exists and is a socket.
file1 -nt file2 True if file1 exists and is newer than file2.
file1 -ot file2 True if file1 exists and is older than file2.
file1 -ef file2 True if file1 and file2 exist and refer to the same file.

For more information type the following command at shell prompt or see test command in our wiki:
bash(1),test(1)

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 36 comments/add one below):

36 comment

  1. I need to check a file on daily basis that is created by anotehr process. The file format is:

    DataFile_MMDDYYYY.csv

    So, I need to get today’s date in MMDDYYYY format, concate that with a string variable, FileName = “DataFile_” + DatePart + “.csv”

    Then look for that FileName file if exists then run a command (sas sendemail.sas).

    How can I achieve that? Thanks.

  2. Hello Volks:
    I would like to look for a File: if it exists – AND – it´smaller (lt/gt) than 1000000, then … echo ” File too small” , return 1 … and so on:

    #!/bin/bash
    FILE=nec2.txt
    if -f [ “$FILE” ] && -f [ “$FILE” -lt 1000000 ] ;
    then
    echo “File $FILE too small”
    else
    echo “File $FILE does not exists”
    fi

    -rw-rw—- 1 cas lokus 31626 2008-12-15 14:00 xnec2.txt

    I use linux 2.4.21-278-smp

    Can you please help there ? Pleas reply to [email protected]
    Many thanks in advance – Petrus

  3. I just hacked this together. I plan to use it for my other scripts. The exit statements make the script exit with a 0 (bash standard for successful completion) or a 1 (non-zero is the bash standard for a failed action)

    #!/bin/bash
    FILE=$1

    if [ -f $FILE ];
    then
    exit 0
    else
    exit 1
    fi

  4. How to check some set of files in the following directory and do the process.
    my statement following is not working: pls explain
    if [ -f “$ROOT/abc/files/CUST*” ]; then
    echo “inside customer file exists”
    else
    echo “No customer file exists”
    fi
    CUST is the post fix of the files, expected to have more than 1 file on some days.

  5. ls D
    blah blah blah
    drwx—— Program Files

    if -d D/Program Files returns FALSE

    It would be nice if I could find some way of successfully testing for names with spaces 🙁

    Cheers,
    Wol

  6. Hi,

    I have /media/USBDisk0 and that the mount point for my USBDisk.
    And a hard link named /media/TheData/Data -> /media/USBDisk0/Data
    When the USB is mounted, the hard link is OK, but If something fail, the hard link is broken…. Can use the if to test the hard link?

    1. you could also have done the following:

      find /home/username/thunderbird-directory/ -iname .parentlock -ok rm {} ;

      it’ll find the file and attempt to remove it, but will ask you first… if you need it to remove it right away, replace -ok with -exec

  7. if [ -e filename ] works for me and checks fine ONLY when I’m logged in as a power broker. It doesn’t test when I log in as a normal user or call the script from a different scheduling tool.

    Please help me ASAP

  8. i need shell script where the i need to connect from one server to another server…
    and check for file *.mediate.log in path /home/apps/ and if found it need to execute a script prescript.sh in the same path and return a status to the server…and if the files doesn’t exist it shud return another status…and if the job fails becoz of any resin it need to return another status…
    Can you please help me with this ASAP…very urgent

  9. I need to check if in
    1.example1.sh test.log exists
    if 1 is yes then execute 2 else execute 5
    2. get the current date from test.log file
    3. get current system date
    4. if date in step 2 + 1 day <=date in step 3 then step 5 else step 6
    5. execute example2.sh
    6.end

    example2.sh
    writes to test.log
    and also contains current date and current time

  10. i want to check if the file exists in a folder:
    if exists(delete the file in the folder)
    else
    create a new file in the same name.

    I tried the above codes which dint work for me.. any help would be of great help..

Leave a Comment