3

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.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Praveen
  • 39
  • 1
  • 2
  • 7
  • 2
    Despite the word "string" in the above proposed duplicate, it doesn't strictly have to be a string. The point is that you can only _return_ an unsigned byte (0-255) from a shell function. – kojiro May 04 '17 at 03:16

3 Answers3

2

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
Mischa
  • 2,240
  • 20
  • 18
  • Thank you :) Its working... I will not use test as my function name. This was just a sample, but my mistake in naming. thanks a lot :) – Praveen May 04 '17 at 06:17
1

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
KeithC
  • 436
  • 1
  • 6
  • 25
  • For an example I pasted this simple code. I am using another function that converts the time (HH:MM) to seconds and this is being called many times. – Praveen May 04 '17 at 06:10
  • This does not answer the OP, they are seeking to compute and return a value from a function. – Bill Gale Dec 01 '20 at 21:26
0

There are some issues in your code.

#!/bin/bash

It works but it is no good idea to define a function called test, because test is a standard Unix program.

test()
{

Write debug output to standard error (&2) instead of standard output (&1). Standard output is used to return data.

  echo "$1" >&2

Declare variables in functions with local to avoid side effects.

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

Use echo instead of return to return strings. return can return only integers.

  echo "$c"
}

var=$(test 10)

If unsure always quote arguments.

echo "$var" >&2
ceving
  • 21,900
  • 13
  • 104
  • 178