其他分享
首页 > 其他分享> > [转]Bash Function & How to Use It {Variables, Arguments, Return}

[转]Bash Function & How to Use It {Variables, Arguments, Return}

作者:互联网

 

原文:https://phoenixnap.com/kb/bash-function

---------------

Introduction

A bash function is a method used in shell scripts to group reusable code blocks. This feature is available for most programming languages, known under different names such as procedures, methods, or subroutines.

This article provides a complete overview of bash functions, how they work, and how to use them.

Bash Function & How To Use It

Prerequisites

 

Note: The Bash (Bourne Again SHell) is considered the default shell in this tutorial. If your default shell is different, try adding the #!/bin/bash shebang to the beginning of the scripts.

What Are Bash Functions?

A bash function is a technique for grouping reusable bits of code under one name for later use. The bash function is like a script within a script.

hello world function bash script

Using functions in bash scripting comes with two benefits:

1. A function is read directly into the shell's memory and stored for later use. Since computer memory is not an issue nowadays, using functions is faster than repeating code.

2. Functions help organize long shell scripts into modular and reusable code blocks. The chunks are easier to develop and maintain.

How to Use Bash Functions?

There are two ways to implement Bash functions:

To use bash functions, follow the outlines below.

Bash Function Syntax

There are two different ways to declare a bash function:

1. The most widely used format is:

<function name> () { 
        <commands> 
}

Alternatively, the same function can be one line:

<function name> () { <commands>; }

2. The alternative way to write a bash function is using the reserved word function:

function <function name> {
        <commands>
}

Or in one line:

function <function name> { <commands>; }

Take note of the following behaviors and tips when using functions:

How to Declare and Call a Function?

A function does not execute when declared. The function's body executes when invoked after declaration. Follow the steps below to create a bash script with various syntax options:

1. Using your favorite text editor, create a shell script called syntax. If you're using Vim, run the following line in the terminal:

vim syntax.sh

2. Add the code below to the shell script:

# syntax.sh
# Declaring functions using the reserved word function
# Multiline
function f1 {
        echo Hello I\'m function 1
        echo Bye!
}
# One line
function f2 { echo Hello I\'m function 2; echo Bye!; }

# Declaring functions without the function reserved word
# Multiline
f3 () { 
        echo Hello I\'m function 3
        echo Bye!
}
# One line
f4 () { echo Hello I\'m function 4; echo Bye!; }

# Invoking functions
f4
f3
f2
f1

syntax.sh shell script

The script does the following:

3. Save the script and close Vim:

:wq

4. Make the syntax.sh file executable:

chmod +x syntax.sh

5. Lastly, run the script to see the output:

./syntax.sh

syntax.sh output in terminal

How to Declare and Call a Function in the Terminal?

To declare and use a function in the terminal:

1. Open the terminal and enter the following line:

my_function () { echo "Hello I'm a function"; echo "Bye!"; }

2. Execute the function by entering the function's name in the terminal:

my_function

my_function terminal function

The output runs the commands in the function's body.

The function only stays defined in the current terminal session. To save for future sessions, add the code to the ~/.bashrc file.

Where is a Bash Function Defined?

To see where a bash function is defined and its contents, enter the following commands in the terminal:

1. Run the bash shell in debugger mode:

bash --debugger

2. Check the function's source file with:

declare -F <function name>

For example:

declare -F my_function

bash debugger location and definition

The output prints the function's name, the line number, and the file location where the function definition is.

3. To see the function's contents, run:

declare -f <function name>

For example:

declare -f my_function

showing function contents in the terminal

The declare built-in in debugging mode allows viewing the function's contents and location without running the code.

 

Note: Learn everything you need to know about using the Bash declare statement.

How to Delete a Bash Function?

If you need to free up a namespace occupied by a function in the current terminal session, run:

unset <function name>

For example:

unset my_function

unsetting a function in the terminal

The function is no longer available in the current terminal session. However, if the code is in the ~/.bashrc file, everything is restored to normal in the next session.

Bash Function Variables

The variables in bash are global by default and accessible from anywhere, including function bodies. Variables defined inside a function are also global. Adding the keyword local makes the term accessible only within the function and the child functions/processes.

In dynamic scoping, a local variable shadows a global variable when the two carry the same name.

Try the following bash script to demonstrate how function variables work in bash:

1. Create a script called variable.sh:

vim variable.sh

2. Add the following code to the script:

var1=1
var2=1
change() {
        echo Inside function
        echo Variable 1 is: $var1
        echo Variable 2 is: $var2
        local var1=5
        var2=5
        echo
        echo After change inside function
        echo Variable 1 is locally $var1
        echo Variable 2 is globally $var2
}
echo Before function invocation
echo Variable 1 is: $var1
echo Variable 2 is: $var2
echo
change
echo
echo After function invocation
echo Variable 1 is: $var1
echo Variable 2 is: $var2

variable.sh shell script

The script shows the following:

3. Save the script and exit Vim:

:wq

4. Change the file permissions to executable:

chmod +x variable.sh

5. Run the script and analyze the results:

./variable.sh

variable.sh output in terminal

The variable values print to the console through the changes made in the script.

Bash Function Arguments

To pass arguments to a function, add the parameters after the function call separated by spaces. The table below outlines the available options when working with bash function arguments.

ArgumentRole
$0 Reserves the function's name when defined in the terminal. When defined in a bash script, $0 returns the script's name and location.
$1$2, etc. Corresponds to the argument's position after the function name.
$# Holds the count of positional arguments passed to the function.
$@ and $* Hold the positional arguments list and function the same when used this way.
"$@" Expands the list to separate strings. For example "$1", "$2", etc.
"$*" Expands the list into a single string, separating parameters with a space. For example "$1 $2" etc.

Follow the steps below to test how the various arguments work in a function.

1. Create a script called arguments:

vim arguments.sh

2. Add the following code into the script:

arguments () {
        echo The function location is $0
        echo There are $# arguments
        echo "Argument 1 is $1"
        echo "Argument 2 is $2"
        echo "<$@>" and "<$*>" are the same.
        echo List the elements in a for loop to see the difference!
        echo "* gives:"
        for arg in "$*"; do echo "<$arg>"; done
        echo "@ gives:"
        for arg in "$@"; do echo "<$arg>"; done
}

arguments hello world

3. Save the script and exit Vim:

:wq

4. Make the script executable:

chmod +x arguments.sh

5. Execute the script:

./arguments.sh

arguments.sh output in terminal

The output displays descriptive messages for each argument used.

Bash Function Return

Bash functions differ from most programming languages when it comes to returning a value from a function. By default, bash returns the exit status of the last executed command in the function's body.

The script below shows how to specify the exit status using return:

1. Create a script and name it test.sh:

vim test.sh

2. Add the following function to the file:

test_function() {
        echo Test
        return 100
}
echo The function\'s output is: 
test_function
echo The exit status is:
echo $?

3. Save and close the text editor:

:wq

4. Change the permissions:

chmod +x test.sh

5. Run the script to see the function's output and exit status:

./test.sh

An alternative method is to echo the function's result and assign the output to a variable. Edit the test.sh script with the following code:

test_function() {
        echo Test
}
result=$(test_function)
echo $result is saved in a variable for later use

This method mimics how most programming languages work when using functions.

 

Note: Check out our bash scripting tutorial on how to run a bash script that features several methods explained.

Conclusion

After going through this tutorial, you should know how to use functions in bash scripting. Next, use our git commands cheat sheet to help you automate repetitive git tasks using bash function

标签:Function,function,Use,Return,script,functions,echo,sh,bash
来源: https://www.cnblogs.com/oxspirt/p/16341009.html