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:
- it is much faster (especially useful in tight loop)
- 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