1

I have a function that returns a value.
But I would like to add some echos for easier debugging. But this scrabbles the result.
Example:

function foo {
   echo "In foo"
   VAR="1234"
   echo "Calculated item"
   echo "$VAR"
}

RESULT=$(foo)
echo "RESULT=$RESULT"

I was expecting to get 1234.
Instead the output is:

RESULT=In foo  
Calculated item  
1234

What is the correct way to fix this?

  • 1) there's no return statement 2) in bash, you can't return a string, it's the output STDOUT that is returned, so this behavior is just normal 3) in 2018, to declare function, just use : f() { } – Gilles Quenot Mar 30 '18 at 11:23
  • @GillesQuenot:Is that definition ok for all platforms? – Jim Mar 30 '18 at 20:44
3

Redirect the debugging output to standard error:

foo () {
   echo 'In foo' >&2
   VAR="1234"
   echo 'Calculated item' >&2
   echo "$VAR"
}

RESULT=$(foo)
printf 'RESULT="%s"\n' "$RESULT"

You could even create a dedicated "debug" function:

debug () {
    printf 'DEBUG: %s\n' "$@" >&2
}

foo () {
   debug 'In foo'
   VAR="1234"
   debug 'Calculated item'
   echo "$VAR"
}

RESULT=$(foo)
printf 'RESULT="%s"\n' "$RESULT"

Output:

$ sh script.sh
DEBUG: In foo
DEBUG: Calculated item
RESULT="1234"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.