Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested function calls in Bash

Tags:

function

bash

Right now, I'm trying to nest one bash function call inside another function call (so that the output of one function is used as the input for another function). Is it possible to nest function calls in bash, as I'm trying to do here?

First, I defined these two functions:

returnSomething()
{
    return 5;
}

funky ()
{
  echo $1;
}

Then, I tried to use the output of one function as the input for the other function. However, this next statement doesn't print the output of returnSomething. Instead, it prints nothing at all.

funky $returnSomething; #Now I'm trying to use the output of returnSomething as the input for funky.
like image 475
Anderson Green Avatar asked May 01 '13 20:05

Anderson Green


1 Answers

You have two problems. One is that return does not set the output of a function, but rather its exit status (zero for success, nonzero for failure). For example, echo foo will output foo (plus a newline), but has an exit status of 0. To control output, use echo or printf:

function returnSomething ()     # should actually be outputSomething
{
    echo 5
}

The other problem is that $returnSomething (or ${returnSomething}) gives the value of a variable named returnSomething:

x=5          # sets the variable x
echo "$x"    # outputs 5

To capture the output of a command, use the notation $(...) (or `...`, but the latter is trickier). So:

function funky ()
{
    echo "$( "$1" )"
}
funky returnSomething    # prints 5

or just:

function funky ()
{
    "$1"          # runs argument as a command
}
funky returnSomething    # prints 5

By contrast, if you do want to capture the exit status of a command, use the special shell parameter ? (which is set to the exit status of a command when it completes):

function returnSomething ()
{
    return 5
}
function funky ()
{
    "$1"          # runs argument as a command
    echo "$?"     # prints its exit status
}
funky returnSomething    # prints 5
like image 178
ruakh Avatar answered Sep 20 '22 11:09

ruakh