The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,969 other subscribers

How to return a string value from a Bash function – Stack Overflow

Posted by jpluimers on 2020/06/17

Cool: you can return strings both as a function result, and by reference: they are explained in the question, second and fourth answer of [WayBack] How to return a string value from a Bash function – Stack Overflow.

Returning them by reference has two important benefits:

  1. it is much faster (especially useful in tight loop)
  2. you can use echo (normally used to return a result) for debugging purposes

I also needed a bit of switch magic which I found at [WayBack] bash – Switch case with fallthrough? – Stack Overflow and array magic (from [WayBack] Array variables) as arrays are far more readable than indirection (on the why not, see [WayBack] BashFAQ/006 – Greg’s Wiki: How can I use variable variables (indirect variables, pointers, references) or associative arrays?).

So here is a function that returns a specific IPv4 octet.

function getIpv4Octet() {

  while [ "${count}" -le 4 ]
  case "${octetIndex}" in
    "1" | "2" | "3" | "4")
  eval $outputVariable="${octet[$octetIndex]}"

You call it like this:

$ getIpv4Octet "" 3 result && echo ${result}


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 )

Twitter picture

You are commenting using your Twitter 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.

%d bloggers like this: