Seung Min Ahn
Seung Min Ahn

Reputation: 31

Shell script's return value is different in ( normal vs. debugging mode ) execution

I was solving this "Factorial function in recursive(= getting n! of argument n)" problem. This is the bash shell script code I came up with. I give one integer as an argument:

#!/bin/bash
# Script name: RecFact.sh
#
# recursive factorial
factorial(){
if [ $1 -eq 0 ]; then
    return 1
fi
pro=`expr $pro \* $1`
factorial `expr $1 - 1`
return $pro
}
pro=1
factorial $1
echo "$?"

The problem is, when I run it on the terminal with 1~5 as the one argument it needs(e.g. ./RecFact.sh 5), the returned value(like 120 for 5) is correct.

But when the argument goes above 5, it gets all wrong(like 208 for 6, instead of 720).

What's really strange is, if I run it in debugging mode(e.g. sh -x ./RecFact.sh 6), the debugger gives the correct value(like 720 for 6) for every input value.

What could be the reason?

Upvotes: 2

Views: 279

Answers (2)

Hardik Sanghvi
Hardik Sanghvi

Reputation: 436

In normal mode i.e when you are executing ./RecFact.sh 6 you are actually executing

bash RecFact.sh 6

since in your script you have #!/bin/bash

But in debug mode

sh -x ./RecFact.sh 6

you are executing using sh. On my system sh has a link to dash. This may be the case in your system too.

bash and dash are two different shells , most commands work the same, but they are different. Hence you are seeing two different outputs.

So in your script if you change #!/bin/bash to #!/bin/sh , it will work fine. Also @employee of the month is correct. Do not abuse $?

Upvotes: 1

user4822941
user4822941

Reputation:

The error code (which you inspect with $?) is of the range 0-255. And indeed, 720 modulo 256 gives you 208.

Instead of abusing $? you should use a dedicated variable to convey the result.

Upvotes: 3

Related Questions