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:

main.sh:

#!/bin/bash
declare VAR
source ./common.sh
var_grabber VAR
echo “VAR is: $VAR”

 

common.sh:

#!/bin/bash

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

string=”$VAR1,$VAR2″
eval $output=\$string
}

As main.sh is run, the return is:

$ bash main.sh
VAR is: var1,var2

In this example, main.sh sources the common.sh 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 main.sh 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.

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s