How to check if file exists in Linux command line

Bash is a Unix shell that can be used to interact with the terminal. It is an important part of Linux. Bash includes commands for system administration, as well as interactive and programming modes, which can be used to perform various tasks including managing user accounts, creating files and directories, copying files around, installing software packages etc. Today, we will see how we can check file presence using bash, command-line or in scripts.

Simply, checking in command-line, using the ls command

dev@ubuntu:/tmp$ ls -l myfile
ls: cannot access 'myfile': No such file or directory

Check using the test command

test -f myfileThis approach is more useful when you want to check in a script (bash or shell)

What is the result?
dev@ubuntu:/tmp$ test -f myfile
dev@ubuntu:/tmp$
dev@ubuntu:/tmp$ echo $?
1

This file does not exist so will cause an exit status of 1

Now, let us create a file and test it again

dev@ubuntu:/tmp$ touch myfile
dev@ubuntu:/tmp$ ls -l myfile
-rw-rw-r-- 1 dev dev 0 Aug 25 20:38 myfile
dev@ubuntu:/tmp$
dev@ubuntu:/tmp$ test -f myfile
dev@ubuntu:/tmp$
dev@ubuntu:/tmp$ echo $?
0
dev@ubuntu:/tmp$