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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.