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:
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
more idiomatic bash:
if [[ ! (-e $myPath && -f $myPath) ]]; then echo 'Path invalid. Stop..' >&2 exit fi