bash function

Bash function looks strange for people who are familiar with other programming languages such as C++, JAVA, etc.

First, you seem to never see a bash function that has (formal) parameters. Although when defining a bash function, you provide parentheses after the function name, there’s nothing in the parentheses, like this:

myfunc()
{
}

But that does not mean you can not pass arguments to the function. For this function, you can pass any number of arguments when calling it.

The second difference than other programming languages is that calling a function does not use parentheses to pass arguments. So the following syntax is wrong:

myfunc("par1","par2","par3","par4")

To call bash function with arguments, just write the arguments after the function name, separating them with spaces:

myfunc "par1" "par2" "par3" "par4"

If you do not want to pass arguments, just type the function name to call it, do not add parentheses. In other words, bash function is considered as an ordinary command.

Since you do not write formal parameters in the parentheses when defining the function, how could you get the arguments inside the bash function? Well, you can get the first argument by $1, the second argument by $2, etc, like this:

myfunc()
{
    echo $1
    echo $2
}

myfunc "par1" "par2"

The third difference of bash function from C/Javascript, etc is that it does not have a return value. So you do not need to specify the return type when defining the function. If you want the function to return a value, e.g., return a string, you can do this by setting a variable inside the function and get the value of the variable after calling the function:

myfunc()
{
    result="myprogrammingnotes.com"
}

myfunc
echo $result

We know bash commands have a status code which can be obtained with $?. You can use $? to get the status code of the last command of the function after calling the function, which can be thought of a return value of the function. You can even use the return command inside a bash function to set the status code to $? and return from the function immediately, then get the return value using $?.

myfunc()
{
    return 123
}

myfunc
echo $?

But you can only return a numeric value in this way.

reference:https://linuxize.com/post/bash-functions/

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply