0

I have a bash function that returns a number by adding 20 to it. At the same time, I would like to display to see what is the input.

function add_nos {
    echo "$1"
    echo $(($1 + 20))
    return 1
}

result=`add_nos $1`
echo $result

When I run the following command -

bash setup.sh 10

I get the following output -

10 30

How can I differentiate between the 2 stmts; ie 1st echo is for debug and 2nd echo is for return value.

2 Answers2

3

Maybe print the debug statement to standard error instead of standard output?

echo "$1" >&2
choroba
  • 9,643
0

Return

The return value is stored in $? after every command/function call. Try this to access it:

function add_nos {
    echo "$1"
    echo $(($1 + 20))
    return 1
}

result=`add_nos $1`
retval=$?  # this is the "return" value of "add_nos"
echo "result: $result"
echo "return: $retval"

See the man page. Also this question and this article.

Stderr

As another answer suggested, stderr is a good place to send debug output. You can also do a lot more than just a return value. Try this:

function add_nos {
    echo "input: $1" >&2
    echo $(($1 + 20))
    echo "done now!" >&2
}

echo "starting script" >&2
result=`add_nos $1`
echo "result: $result"

Then run it with and without debug output by redirecting stderr:

$ bash setup.sh 10  
starting script
input: 10
done now!
result: 30

$ bash setup.sh 10 2>/dev/null
result: 30

$ bash setup.sh 10 2>logfile
result: 30

$ cat logfile
starting script
input: 10
done now!
Jacktose
  • 939
  • 6
  • 9