Bash – Returning more than just a code

I do most of my scripting in upper level languages, however recently I was tasked with “fixing” a bash shell script another person wrote where I work.  Naturally that meant I had to rewrite it since it wasn’t up to par.  I grew tired of using global variables since it leaves the entire namespace limited.  After research, I found a way to return a string from a function to the calling function/main script.  I figured I’ll share.

Here’s a simple example of string returning that is quite useful when applied in returning comma or colon-delimited strings of data for parsing.  This example returns a couple of comma-delimited variables in a string:

declare VAR
source ./
var_grabber VAR
echo “VAR is: $VAR”


function var_grabber() {
local output=$1
local VAR1=”var1″
local VAR2=”var2″
local string=””

eval $output=\$string

As is run, the return is:

$ bash
VAR is: var1,var2

In this example, sources the script to allow the function to be used.  In a nutshell, call the function with just the name of a variable that will hold the data, without the dollar-sign.  In the function, pass the first argument (the variable name) to a local variable, and pass the reference to a string to the local variable holding that variable name.  (output, in this case)
The eval sets it up properly, and in the VAR variable will hold the string.  From there it can be parsed and used as needed.

I figured I’d share this since it allows the ability to apply message-passing logic to bash scripting, for those that are used to it.  I know there are many other ways to do this, but this was closer to Perl style which I am used to.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.