skip to content
Alvin Lucillo

Variable and file check

/ 1 min read

💻 Tech

The example below shows how to validate a variable and file.

The first if condition checks whether FILE1 variable is set or not with -z. If it is not set or if it set with blank value in the terminal session or inline as you call the script, the condition will result to true, demonstrated by the example below.

The second if condition checks first if the file with file name from the FILE1 variable exists with -f then negates it with !, meaning the condition passes if the file existence check is a false.

Script: test.sh

#!/bin/bash
if [[ -z "${FILE1}" ]]; then
        echo "FILE1 is not set"
        exit 1
fi

if [[ ! -f "${FILE1}" ]]; then
        echo "FILE1 does not exist"
        exit 1
fi

Script execution in the terminal:

./test1.sh                     ## FILE1 is not set
FILE1="" ./test1.sh            ## FILE1 is not set
FILE1="test1.txt" ./test1.sh   ## test1.txt does not exist