Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from a function in shell script [duplicate]

I would like to pass an argument to a function and return a calculated value from it to be stored for further process. Below is the sample code.

#!/bin/bash

test()
{
    echo $1

    c=$(expr $1 + "10000")

    return $c
}

var=$(test 10)

echo $var

I would like to get the value of c stored in var. Can anyone please help in this case.

like image 910
Praveen Avatar asked Feb 04 '26 20:02

Praveen


2 Answers

The "return value" of a function as you used it is stdout. "return" will set exit status ($?), which you probably have no use for. "test" is probably a bad choice of name, since it's taken (qv. man test). So:

$ Test() { expr $1 + 10000; }
$ var=$(Test 10)
$ echo $var
10010
like image 96
Mischa Avatar answered Feb 07 '26 10:02

Mischa


if all you wish to do is add 10000 to your input, then a function is overkill. for this, wouldnt this work?

your_arg=10
var=$(( ${your_arg}+10000 ))
echo $var
like image 20
KeithC Avatar answered Feb 07 '26 10:02

KeithC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!