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 if_10.sh to check whether the file exists or not in the current directory as follows:

#!/bin/bash 
read filename 
if test -e $filename 
then 
    echo "file exists" 
else 
    echo " file does not exist" 
fi 

Let's test the program as follows:

    $ chmod +x if_10.sh
    $ ./if_10.sh
  

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.