Reputation: 3278
I have a condition which seems to always be evaluated as true.
#!/bin/bash
checkFolder() {
echo "[checkFolder]"
echo "check $1"
[ -n "$1" ] && [ -d "$1" ] && return 0
echo "[/checkFolder]"
return 1
}
rootFolder=$1
echo "check $rootFolder"
checkFolder "$rootFolder"
echo "res: $res" # !! <--- I omitted this test line, as I thought it was irrelevant.
echo "ret: $?"
When I execute my script, any path will give me a return value of 0. Which means that any string I provide seems to be seen as non-empty as well as an existing directory. I tried with:
./myScript.sh "."
./myScript.sh ""
./myScript.sh "wqert"
I will aways get a return value of 0. How comes? If I run this command in my terminal:
param=""
[ -n "$param" ] && [ -d "$param" ] && echo ok
# returns nothing
param="hello"
[ -n "$param" ] && [ -d "$param" ] && echo ok
# returns nothing
param="/home"
[ -n "$param" ] && [ -d "$param" ] && echo ok
# returns "ok"
Why doesn't it work in my script?
Upvotes: 1
Views: 124
Reputation:
What the command return
changes is the "exit code" of the function.
Add this:
checkFolder "$rootFolder"
echo "the exit code was $?"
And see the effect of your return 0
and return 1
.
Upvotes: 1
Reputation: 123480
$?
is the exit code of the last executed command. In your case, the last executed command is echo
, not checkFolder
.
If you want to execute other commands between running a command and checking its status, assign it to a variable with myvar=$?
Upvotes: 4