How to check if file exists in Linux command line

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

[email protected]:/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?
[email protected]:/tmp$ test -f myfile
[email protected]:/tmp$
[email protected]:/tmp$ echo $?
1

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

Now, let us create a file and test again

[email protected]:/tmp$ touch myfile
[email protected]:/tmp$ ls -l myfile
-rw-rw-r-- 1 dev dev 0 Aug 25 20:38 myfile
[email protected]:/tmp$
[email protected]:/tmp$ test -f myfile
[email protected]:/tmp$
[email protected]:/tmp$ echo $?
0
[email protected]:/tmp$