How To Check If File Exists In Linux Bash? – POFTUT

How To Check If File Exists In Linux Bash?


Linux bash have different file and directory related functions to create, delete, change and check existence. In this tutorial we will look how to check a file or directory if it exists.

Check File Existence

We will use bash test mechanism. Bash test mechanism have two formats where we can use followings.

  • test -f FILENAME
  • [ -f FILENAME]

Square brackets format is preferred in conditional usage like ifand switch . In this example we will check if  file named myinput.py exists.

$ if [ -f myinput.py ]; then echo "File Exist"; fi
Check File Existence
Check File Existence

Check If File Not Exist

Another use case it checking existing and returning the reverse answer or NOT’ing the Boolean result. If the file exist this will return not in if conditional. We will use ! which is used by programming languages for Boolean reversing. In this example if the file named “myfile” do not exist we will print message.

$ if [ ! -f myfile ]; then echo "File Do Not Exist"; fi
Check If File Not Exist
Check If File Not Exist

Check Existence with test Command

As we stated previous test is the same with [ -f FILE] . It just provides a bit different syntax. We will use testkeyword with -f and file name. In this example we will check file named myinput.py and print result with $?.

$ test -f myinput.py
$ echo $?
Check Existence with test Command
Check Existence with test Command

As we can see the result is 0 which means successful or true .

Test If Directory Exists

We can also check given directory existence. We will use -d flag in order to test. In this example we will check if the directory named backup exists.

$ if [ -d backup ]; then echo "Directory Exists"; fi
Test If Directory Exists
Test If Directory Exists

LEARN MORE  Cockpit Easy and Web Based Administration of Linux

Leave a Comment