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
[email protected]:/tmp$ ls -l myfile
ls: cannot access 'myfile': No such file or directory
Check using the test command
test -f myfile
This 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 it 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$