Https://kodekloud.com/topic/lab-functions/

Q. The script /home/bob/sum.sh does not seem to be functioning as expected. We would like the script to print the sum of 2 numbers. However it doesn’t seem to be doing that.
Identify and fix the issue.
→ the soln is below

function add(){
  sum=$(( $1 + $2 ))
  echo $sum
}

result=$(add 3 5)
echo "The result is $result"

But my question is when fun is called in [result=$(add 3 5)], it should print echo $sum value also on screen as echo is use to print on screen. After that "The result is $result" should be printed. Please elaborate.

Hi @uzmashafi061

When you call echo inside a function, the output is returned to the stdout and shows you 8 in our case. But when we do result=$(add 3 5) the output is redirected to the variable result and now we echo the variable to show the result

Regard

ok, so the output of above code will be
8
The result is 8
correct?

@uzmashafi061

The first 8 will not be shown because the output is redirected to the variable

image

1 Like