Friday, February 27, 2009

BASH functions with multiple results

BASH functions are limited...
Check Bash-Prog-Intro-HOWTO

... but sometimes it is required to have BASH functions that returns multiple results.
In case of strings or numbers next idea could be applied:
#!/bin/bash

# get_rtrn
# get return result part
# params:
# $1 - return result string
# $2 - number of part to be returned
# returns:
# return result part
function get_rtrn(){
echo `echo $1|cut --delimiter=, -f $2`
}

function some_func(){
# calculate result 1
# ...
RES1="string1"

# calculate result 2
# ...
RES2="13"

# calculate result 3
# ...
RES3="value3"

# return results
echo "$RES1,$RES2,$RES3"
}

# function call
RESULT=`some_func`
echo "RESULT = $RESULT"

# get parts of result
RES1=`get_rtrn $RESULT 1`
RES2=`get_rtrn $RESULT 2`
RES3=`get_rtrn $RESULT 3`

echo "RES1 = $RES1"
echo "RES2 = $RES2"
echo "RES3 = $RES3"

Script output:
bash test.sh
RESULT = string1,13,value3
RES1 = string1
RES2 = 13
RES3 = value3

No comments: