Get the App
SLTechnology News&Howtos  ›  Servers  › 

Methods of using functions in Bash Shell scripts

Shulou Source: shulou.com Published: 2022-06-02 04:36:07 10月30日 Update

How to use functions in Bash Shell scripts? This problem may be often seen in our daily study or work. I hope you can gain a lot from this question. The following is the reference content that the editor brings to you, let's take a look at it!

Create the first function in the Shell script

Create the first function in the shell script to display the output "Hello World!" . Use the following code to create the shell script "script.sh".

# vim script.shemaking bind bind Bash funHello () {echo "Hello World!";} # Call funHello from any where in script like belowfunHello

Execute the script:

# sh script.shouput:Hello World!

How to pass parameters to a function in a shell script

Passing parameters to a function is similar to passing parameters from shell to a command. The function receives $1, $2... The parameters of, etc. Use the following code to create a shell script.

# vim script. Fourth Argument Fourth Argument: 4) {echo "First Argument: $1" echo "Second Argument: $2" echo "Third Argument: $3" echo "Fourth Argument: $4"} # Call funArguments from any where in script using parameters like belowfunArguments First 2 3.5 Last

Execute the script:

# sh script.shOuput:First Argument: FirstSecond Argument: 2Third Argument: 3.5Fourth Argument: Last

How to receive a return value from a function in a Shell script

Sometimes we also need to return a value from a function. Use the following example to get the return value from a function in the shell script.

# vim script.shrunken bind bind Bash ReturnValues () {echo "5"} # Call funReturnValues from any where in script and get return valuesvalues=$ (funReturnValues) echo "Return value is: $values"

Execute script

# sh script.shOuput:5

How to create a recursive function in a shell script

The function that calls itself is called a recursive function. The following example shows how to print 1 to 5 digits using a recursive function.

# vim script.shendarbinram Bash funRecursive () {val=$1if [$val-gt 5] thenexit 0elseecho $valfival=$ ((val+1)) funRecursive $val # Function calling itself here} # Call funRecursive from any where in scriptfunRecursive 1

Execute the script:

# sh script.shOuput:12345 Thank you for reading! After reading the above, do you have a general idea of how to use functions in Bash Shell scripts? I hope the content of the article will be helpful to all of you. If you want to know more about the relevant articles, you are welcome to follow the industry information channel.

Tags: Functions scripts content parameters creative recursive methods code articles examples questions commands numbers more look industry information information channels faceted channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Tech Info Xiaomi Redmi Huawei