Home > other >  Bash return value of test -e $file always returns false
Bash return value of test -e $file always returns false

Time:01-23

I would like to check if a path is valid in Bash. However the lower code always returns false, even if the path is valid.

# Test if path is valid
mytest=$(test -e $myPath && test -f $myPath)

if [[ ! $mytest ]]; then 
        echo 'Path invalid. Stop..'
        exit 
fi

How can I improve the code?

CodePudding user response:

$() command substitution captures the output of a command, not the exit status.

  • $mytest will be empty
  • [[ ... ]] with only one operand (not counting !) returns "true" if the operand is not empty. Because $mytest is empty, the test result is "false negated"

To fix it:

  1. following your style:

    test -e "$myPath" && test -f "$myPath"   # quote your variables
    mytest=$?                                # capture the exit status immediately
    
    if [[ $mytest -ne 0 ]]; then 
        echo 'Path invalid. Stop..'
        exit 
    fi
    
  2. more idiomatic bash:

    if [[ ! (-e $myPath && -f $myPath) ]]; then 
        echo 'Path invalid. Stop..' >&2
        exit 
    fi
    
  • Related