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.

1
  • 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. Commented May 4, 2017 at 3:16

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

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 :)
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

2 Comments

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.
This does not answer the OP, they are seeking to compute and return a value from a function.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.