Matt Dunn
Matt Dunn

Reputation: 5420

Return value of function when substituted into local variable

Say I have the following two Bash scripts:

Version #1:

#!/bin/bash

function bar
{
  if true; then
    echo "error" >&2
    exit 1
  fi
  echo "bar"
}

function foo
{
  local val=`bar`
  echo $?
  echo "val: $val"
}

foo

With version #2 second having a slightly different foo:

function foo
{
  val=`bar` #note no 'local'
  echo $?
  echo "val: $val"
}

Version #1 gives me the following output:

error
0
val:

Whilst version #2 gives me this:

error
1
val:

The inclusion of local in #2 appears to hide the return value of bar.

Am I correct in thinking this is because local is itself a function, and is returning 0? And if so, is there a way around this and make val a local variable, but still test the return value of bar?

Upvotes: 3

Views: 390

Answers (1)

SiegeX
SiegeX

Reputation: 140547

Yes, you are reading the return value of local which was successful. The fix is to separate the variable declaration from its definition like so:

#!/bin/bash

function bar
{
  if true; then
    echo "error" >&2
    exit 1
  fi
  echo "bar"
}

function foo
{
  local val
  val=$(bar)
  echo $?
  echo "val: $val"
}

foo

Output

$ ./localtest
error
1
val:

Upvotes: 1

Related Questions