Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash function with parameters

I am trying to understand how to work with functions (that receive a argument) in bash. I did not get my code to work, the following code exemplifies my difficulties:

#!/bin/bash

fruit_code () {
        if [[ "$1" == "apple" ]]; then
                code=1
        else
                code=0
        fi

        return $code
}


for var in apple orange banana apple; do
        code=fruit_code $var
        echo $code
done

The shell (bash) complains saying:

apple: command not found
orange: command not found
banana: command not found
apple: command not found

So it seems the passing of parameters is not working propperly. I can not see where I am going wrong. Any help is very much appreciated. Why does it not work? What changes shoyld I do to make it work? Wish to thank you all in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Kind regards
Miguel

>Solution :

The first problem is that if you want to execute a command and capture its output to a variable, you need to use command substitution:

code=$(fruit_code "$var")

The second problem is that your function doesn’t write anything to standard output; it returns an exit status. That is automatically assigned to $? after you call the function. Use this instead:

fruit_code "$var"
echo $?

Finally, the convention in shell is for a 0 exit status to indicate success and a non-zero value failure. In this case, your function "succeeds" if the argument is not apple.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading