Montag, 3. März 2014

Bash - Returning function status and error message at the same time

Fortunately the bash is Turing complete so one can do advanced programing task with it - if there is no other choice to pick a proper dynamically typed scripting language like Python, Ruby or Perl.

Quick detour: Much to my regret, in German Linux magazine long term author of the Perl snapshot series, Michael Schilli, admitted that over the past years Perl got less important. He's part the Perl comunity since a very long time, so this statement might be even more an indicator for looking at the newer kids on the block.

Anyway, I recently found my self again doing rather complex tasks with the bash. I was prototyping some logic which will eventually be implemented in some other (proper ;-) ) language. At some point I started combining two very basic things:
  • returning true or false from a function ( return zero or non-zero)
  • returning a string from a function ( via echo to the standard output of the subshell the function is running in)

Combining the two gave my some nice syntax which kind of resembles a common C programing pattern:

function isGreaterThan() {
    local firstNo=$1
    local secondNo=$2

    if [ ! ${firstNo} -gt ${secondNo} ]; then
        echo "${firstNo} is not greater than ${secondNo}"
        return 1

    return 0

# main

if errorMsg=`isGreaterThan 3 1`; then
    echo "here comes more logic"
    echo "got error: ${errorMsg}"
The function isGreaterThan returns the result of the evaluation as normal return codes. Additionally, in case of a false an error message is given back. One level above the error message is received by calling the function in a subshell (I prefer the old backticks syntax over the new brackets notation).

This nice construct comes with the usual limitations of a subshell operation - the code inside the subshell can read the outer variables but can't alter them.

Keine Kommentare:

Kommentar veröffentlichen