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,030
  • 21
  • 100
  • 124
codepk
  • 605
  • 2
  • 10
  • 22
  • 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,030
  • 21
  • 100
  • 124
Govind Parmar
  • 19,325
  • 7
  • 50
  • 80
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,030
  • 21
  • 100
  • 124
Mandar Pande
  • 11,401
  • 15
  • 43
  • 70