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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
codepk
  • 605
  • 2
  • 10
  • 23
  • change return prod to echo $prod and re-try. ref: http://stackoverflow.com/questions/8742783/returning-value-from-called-function-in-shell-script – A Lan Oct 09 '13 at 03:10

2 Answers2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • 1
    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` – codepk Oct 09 '13 at 03:08
  • What should I do if I want to call it multiple times and store result? – codepk Oct 09 '13 at 03:18
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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mandar Pande
  • 12,250
  • 16
  • 45
  • 72