Very simple question

Hi, guys, I'm a new comer here. I'm studying Unix Shell and I met a problem confusing me a lot. Here it is :
script 1:

#!/bin/sh
# scriptname : do_increment
increment(){
	sum=`expr $1 + 1`
	return $sum		# Return the value of sum to the script.
}
echo -n "The sum is "
increment $1			# Call the increment; pass 5 as a parameter.
				# 5 becomes $1 for the increment function.
echo "ha"
echo $?				# The return value is stored in $?.
echo "The sum is $sum"		# The variable 'sum' is known to the function.
				# and is also known to the main script.
command-line and result 1:
$ ./do_increment 7
The sum is ha
0
The sum is 8

script 2:

#!/bin/sh
# scriptname : do_increment
increment(){
	sum=`expr $1 + 1`
	return $sum		# Return the value of sum to the script.
}
echo -n "The sum is "
increment $1			# Call the increment; pass 5 as a parameter.
				# 5 becomes $1 for the increment function.
echo $?  # The return value is stored in $?.
echo "ha"				
echo "The sum is $sum"		# The variable 'sum' is known to the function.
				# and is also known to the main script.

command-line and result 2:

$ ./do_increment 7
The sum is 8
ha
The sum is 8

My question is : why are the results different just because I put the "echo 'ha'" before or after the "echo $?"

Thx a lot!

It's different because $? holds the result of the previous command.

echo 'ha' will return 0, whereas increment 7 will return 8.

1 Like

OMG, I got u ! Thx