Search code examples
bashtelnet

return value of bash shell


I am trying to learn linux bash scripting. I have a script and I want to get the return value of this script and store it in a variable.

Any help is welcome.

Thank you in advance.

#!/bin/bash
HOST_NAME=$1

{ echo "105" ; sleep 5; } | telnet $HOST_NAME 9761;

Solution

  • To avoid confusion don't think/talk of it as a return value, think of it as what it is - an exit status.

    In most programming languages you can capture the return value of a function by capturing whatever that function returns in a variable, e.g. with a C-like language :

    int foo() {
        printf("35\n");
        return 7;
    }
    
    void main() {
        int var;
        var=foo();
    }
    

    the variable var in main() after calling foo() will hold the value 7 and 35 will have been printed to stdout. In shell however with similar-looking code:

    foo() {
        printf "35\n"
        return 7
    }
    
    main() {
        local var
        var=$(foo)
    }
    

    var will have the value 35 and the unmentioned builtin variable $? which always holds the exit status of the last command run will have the value 7. If you wanted to duplicate the C behavior where 35 goes to stdout and var contains 7 then that'd be:

    foo() {
        printf "35\n"
        return 7
    }
    
    main() {
        local var
        foo
        var=$?
    }
    

    The fact that shell functions use the keyword return to report their exit status is confusing at first if you're used to other Algol-based languages like C but if they used exit then it'd terminate the whole process so they had to use something and it quickly becomes obvious what it really means.

    So when taking about shell scripts and functions use the words "output" and "exit status", not "return" which some people in some contexts will assume means either of those 2 things, and that'll avoid all confusion.

    Btw to avoid making things even more complicated I said above that $? is a variable but it's really the value of the "special parameter" ?. If you really want to understand the difference right now then see https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameters for a discussion of shell parameters which includes "special parameters" like ? and #, "positional parameters" like 1 and 2, and "variables" like HOME and var as used in my script above.