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,155 other followers

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() {
  IPv4=$1
  octetIndex=$2
  outputVariable=$3

  slice="${IPv4}"
  count=1
  while [ "${count}" -le 4 ]
  do
    octet[${count}]="${slice%%.*}"
    slice="${slice#*.}"
    count=$((count+1))
  done
   
  case "${octetIndex}" in
    "1" | "2" | "3" | "4")
      ;;
    *)
      octetIndex="4"
      ;;
  esac
  eval $outputVariable="${octet[$octetIndex]}"
}

You call it like this:

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

–jeroen

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 )

Google photo

You are commenting using your Google 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: