2

Is this the correct syntax for parameterized functions?

#!/bin/bash

twoPow()
{
    prod=1
    for((i=0;i<$1;i++));
    do
        prod=$prod*2
    done
    return prod
}

echo "Enter a number"
read num
echo `twoPow $num`

Output:

bash sample.sh

Enter a number

3

sample.sh: line 10: return: prod: numeric argument required

Part 2:

I removed the return, but what should I do if I want to run multiple times and store results like below? How can I make this work?

#!/bin/bash

tp1=1
tp2=1

twoPow()
{
    for((i=0;i<$1;i++));
    do
        $2=$(($prod*2))
    done
}

twoPow 3 tp1
twoPow 2 tp2
echo $tp1+$tp2
1

2 Answers 2

4

In Bash scripts you can't return values to the calling code.

The simplest way to emulate "returning" a value as you would in other languages is to set a global variable to the intended result.

Fortunately in bash all variables are global by default. Just try outputting the value of prod after calling that function.

Sign up to request clarification or add additional context in comments.

2 Comments

This works: #!/bin/bash prod=1 twoPow() { for((i=0;i<$1;i++)); do prod=$(($prod*2)) done } echo "Enter a number" read num twoPow $num echo $prod
What should I do if I want to call it multiple times and store result?
0

A sample Bash function definition and call with a few parameters and return values. It may be useful and it works.

#!/bin/sh

## Define function
function sum()
{

 val1=$1

 val2=$2

 val3=`expr $val1 + $val2`

 echo $val3

}

# Call function with two parameters and it returns one parameter.
ret_val=$(sum 10 20)
echo $ret_val

1 Comment

expr is not needed for arithmetic anymore; use val3=$(( val1 + val2 )) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.