1

I have used 'return' to return number from shell function, Also I know 'echo' is used to return string from function.

1. return number from shell function

function test1()
{
#some handling
return 0
}

2. return string from shell function

function test2()
{
# some handling
echo "$data"
}

I have a case where I need to return both number and string from shell function.

3. return number and string from shell function

dummy algorithm

function validate()
{
var=$2
if var==something
    return 1
else
    # get modified varible
    modifiedvar=call(var)
    return 0 modifiedvar
}
validate "string"

What is the best way to do it?

8
  • Would it be an option to place the results in global variables of the script that you modify in your function? Commented Oct 19, 2020 at 12:33
  • 3
    return is not used to "return" a number but to exit a function with an exit code. Commented Oct 19, 2020 at 12:33
  • 3
    Relating unix.stackexchange.com/questions/408543/… Commented Oct 19, 2020 at 12:34
  • @JeffSchaller given link is not related to my question Commented Oct 19, 2020 at 12:36
  • 2
    And would you mind to explain why? You want to return two results, the linked question is about "multiple" results. Note that "number and string" is actually irrelevant, as shell variables are untyped (save for array variables, which are arrays of untyped variables). Commented Oct 19, 2020 at 12:39

2 Answers 2

4

You can capture the string with command substitution, and capture the "number" with the return status:

f() {
  echo "Don't panic"
  return 42
}

result=$(f)
status=$?

echo "The function returned >$result< and $status"
The function returned >Don't panic< and 42

Bear in mind that the return status is a number between 0 and 255:

$ f() { echo "$1"; return $2; }
$ result=$(f "big number" 300); status=$?
# ........................^^^
$ echo "The function returned '$result' and $status"
The function returned 'big number' and 44
# .....................................^^
$ result=$(f "small number" -300); status=$?
# ..........................^^^^
$ echo "The function returned '$result' and $status"
The function returned 'small number' and 212
# .......................................^^^
1

Is something like this you're looking for?

script:

#!/bin/bash

var="$1"

function f() {
  if [[ -z "$var" || "$var" = "error" ]]; then
    return 1
  else
    var="bar"
    return 0
  fi
}

if f; then
  echo "function returned $?"
  echo "$var OK"
else
  echo "function returned $?"
  echo "error"
fi

$ ./script
function returned 1
error
$ ./script "error"
function returned 1
error
$ ./script "foo"
function returned 0
bar OK

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.