0

I have the following code inside a unix file with the name func.sh :

function sum {
var=$1
result=expr $var * 100
echo $result
}

export -f sum

I want to be able to call this function from command line hence i do this :

. ./func.sh

I check whether the function is properly exported or not with the below command : declare -x -F

I can see the line : declare -fx sum

But i am unable to run the function from command line . It gives an error :

sum 10 -bash: 10: command not found

Can someone throw some light on what the issue is here ?

Subhayan Bhattacharya
  • 5,407
  • 7
  • 42
  • 60
  • 1
    Maybe try `result=$((var * 100))`... – l'L'l May 25 '16 at 11:50
  • Possible duplicate of [How can I add numbers in a bash script](http://stackoverflow.com/questions/6348902/how-can-i-add-numbers-in-a-bash-script), and [Multiplication in Bash](http://stackoverflow.com/questions/11039876/multiplication-on-command-line-terminal-unix). – l'L'l May 25 '16 at 11:53
  • Your don't need to export if your script just contain functions, just source it. – SLePort May 25 '16 at 11:55

1 Answers1

2

You have defined the function correctly but a statement inside the function is causing the error.

You cant do:

result=expr $var * 100

You need to get the result of expr using subshell execution($() recommended) or using backticks; its better to use bash's $(()) instead of calling an external process(expr)

$ function sum { var=$1; result=$(($var * 100)); echo $result; }
$ export -f sum
$ sum 10
1000
riteshtch
  • 8,629
  • 4
  • 25
  • 38
  • Also, capturing the output only to print it again is unnecessary; `function sum { expr "$1 * 100"; }` would do the same thing. – chepner May 25 '16 at 13:23