Use a shell function, check if a file exists, true or false

This script uses a shell function to check if a file exists (-f). It returns 0 (zero) if the file exists and 1 if it does not exist. You can write your own check functions for checking if a directory (-d) exists, if a file is writable (-w). See “man test” for all check you could do within the if clause.

#!/bin/sh
# Name: isfile.sh
# Author: kdguntu@gmail.com
# Function: Check if a file exists
# Parameter: none
# Copyright: 2011 kdguntu@gmail.com GNU GPL v3
# http://www.gnu.org/licenses/gpl.html 
FILE="myfile.txt"
isfile() {
if [ -f "$1" ];
  then
    return 0
  else
 echo "File $1 not found"  return 1
fi
}
 
if ! isfile "$FILE";then echo "Please provide $FILE"; exit 1; fi

There might be a confusion between the exit code and the return code.

An exit code stops the program with an (invisible but interceptable) code.

exit 0 means the program exits without errors
exit 1-255 means the program exits with an error code.
You could use your own exit code numbers here, depending on the type of error.
For example exit 2 means file not found, exit 3 means configuration error, etc…
One can “see” this exit code by doing a echo $? when the program finishes

A return code of a function, like the function isfile() from above returns true (0) or false (1)

This entry was posted in bash, cut, function, linux, regex, sed, Uncategorized, windows and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *