1

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?

5
  • 2
    Do you believe that setting a variable named param will result in $1 taking on that value? Commented Oct 28, 2015 at 22:58
  • The script, ./myScript.sh, works fine for me. Commented Oct 28, 2015 at 23:01
  • For the command in the termianl, that was a mistake, I just corrected it. However, in my script function checkFolder, $1 does take the argument passed as a value. So my problem remains. Commented Oct 28, 2015 at 23:02
  • 2
    @kaligne So, now you have your answer: that echo line is relevant. It sets an exit code and the final echo "ret: $?" returns the exit code of the preceding echo statement. Commented Oct 28, 2015 at 23:13
  • Thanks for the hint, I realised the problem came from a line I omitted, as I thought it was irrelevant here. I added it in my post: echo "res: $res", which comes before my call to $?. So now I guess an echo returns the value 0 here? Is there an other way for me to retrieve the return value aside from the variable $? ? Commented Oct 28, 2015 at 23:13

2 Answers 2

4

$? 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=$?

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.