0

I am reading the book The Linux Command Line and in the section 27 it teach me how to write a shell script, and in the File Expressions section, it said :

The script evaluates the file assigned to the constant FILE and displays its results as the evaluation is performed. There are two interesting things to note about this script. First, notice how the parameter $FILE is quoted within the expressions. This is not required, but is a defense against the parameter being empty. If the parameter expansion of $FILE were to result in an empty value, it would cause an error (the operators would be interpreted as non-null strings rather than operators).

I don't understand "the operators would be interpreted as non-null strings rather than operators", can anyone give me an example? Thanks.

The original code is:

#!/bin/bash
# test-file: Evaluate the status of a file
FILE=~/.bashrc
if [ -e "$FILE" ]; then
    if [ -f "$FILE" ]; then
        echo "$FILE is a regular file."
    fi
    if [ -d "$FILE" ]; then
        echo "$FILE is a directory."
    fi
    if [ -r "$FILE" ]; then
        echo "$FILE is readable."
    fi
    if [ -w "$FILE" ]; then
        echo "$FILE is writable."
    fi
    if [ -x "$FILE" ]; then
        echo "$FILE is executable/searchable."
    fi
else
    echo "$FILE does not exist"
    exit 1
fi
exit
Onns
  • 3

1 Answers1

0

If the value of $FILE is the empty string and you don't quote the $FILE then your if [ -e $FILE ]; then becomes if [ -e ]; then. The rule of the [ command is that if there is only one value between the [ and the ] then this is true if the value is not the empty string, and false if it is the empty string (so if [ "" ]; then would take the else).

With the quoting, then if [ -e "$FILE" ]; then becomes if [ -e "" ]; then. This has 2 alues between the [ and the ], so a different rule applies.

icarus
  • 17,920