Wednesday, 13 May 2020

Bash Script - return value in bash functions

These are my findings while exploring various ways of return values in Bash functions

1. return value is stored in $?. So we have to first call the function and extract return value from the exit status
function func1() {
  echo "return value is stored in '$?'"
  myvar1=dev1
#  return myvar1 - this is not allowed. Only a numerical return value is allowed
  myvar1=22
  return $myvar1
}

func1
val1=$?
echo "result1: $val1"
# result1: 22

2. modify a global variable to serve as 'return value'
function func2() {
  echo "modify global variable to serve as return value"
  myvar2=dev2
}

func2
val2=$myvar2
echo "result2: $val2"
# result2: dev2

3. write to stdout and capture the value in a variable. this works only if you have one echo in the function. otherwise all the echo statements are concatenated as function output.
function func3() {
  echo "write to stdout and capture value in var"
  local myvar3=dev3
  echo "$myvar3"
}

val3="$(func3)"
echo "result3: $val3"
# result3: write to stdout and capture value in var dev3


No comments:

Post a Comment