How To Check If File Exists In Linux Bash?

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/check-file-exists-linux-bash/
PINTEREST
PINTEREST
INSTAGRAM

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.

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.

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 $?.

Check Existence with test Command

Check Existence with test Command

As we can see the result is 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.

LEARN MORE  Nmap Host Discovery with Examples

Test If Directory Exists

Test If Directory Exists

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/check-file-exists-linux-bash/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)