File handling with the if command

You have already learned about how to use the test command for checking various file operations such as checking the file's permissions and similar other attributes. A command's task in any script is to check whether the file or folder is present or not. Then, accordingly, we need to proceed. We will see how to use the if command along with the test command.

Use the simple script to check whether the file exists or not in the current directory as follows:

read filename 
if test -e $filename 
    echo "file exists" 
    echo " file does not exist" 

Let's test the program as follows:

    $ chmod +x
    $ ./

The following will be the output after executing the preceding commands: ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.