Linux_《 Chapter 17 learning summary of Linux command line and shell script programming

Time:2021-7-21

Time: Monday, October 09, 2017
Note: part of the content of this article is extracted from the book “complete collection of Linux command line and shell script programming”, and the copyright belongs to the original author《 Linux command line and shell script programming Encyclopedia (Third Edition) Chapter 17 learning summary

Chapter 17: creating functions

Contents of this chapter

Basic script functions
Return value
Using variables in functions
Generic group variables and functions
Function recursion
Create Library
Using functions on the command line

17.1 basic script functions

17.1.1 creating functions

Format 1

function name{
    commands
}

Format 2

name(){
    commands
}

explain

The name property defines a unique name given to the function
Commands is one or more bash shell commands that make up a function

17.1.2 using functions

Write test1.sh script

#!/bin/bash

function func1 {
    echo "This is an example of a function"
}

count=1
while [ $count -le 5 ]
do
    func1
    count=$[ $count + 1 ]
done

echo "This is the end of the loop"
func1
echo "Now this is the end of the script"

Functions need to be defined before they can be used

Write test2.sh script

#!/bin/bash

count=1
echo "This line comes before the function definition"

function func1 {
    echo "This is an example of a function"
}

while [ $count -le 5 ]
do
    func1
    count=$[ $count + 1 ]
done
echo "This is the end of the loop"
func2
echo "Now this is the end of the script"

function func2 {
    echo "This is an example of a function"
}

The function name must be unique, otherwise the newly defined function will override the original function

Write test3.sh script

#!/bin/bash

function func1 {
    echo "This is the first definition of the function name"
}

func1

function func1 {
    echo "This is a repeat of the same function name"
}

func1
echo "This is the end of the script"

17.2 return value

The bash shell will treat the function as a small script and return an exit status code at the end of running

17.2.1 default exit status code

By default, the exit status code of a function is the exit status code returned by the last command in the function
After the function is executed, you can use the standard variable $? To determine the exit status code of the function
You can only judge whether the last command in the function runs successfully, but not other commands in the function
It's dangerous to use the default exit status code of a function

Write test4.sh script

#!/bin/bash

func1() {
    echo "trying to display a non-existent file"
    ls -l badfile
}

echo "testing the function:"
func1
echo "The exit status is: $?"

17.2.2 using the return command

Use the return command to exit the function and return the exit status code that specifies an integer value
The function returns the value as soon as it is finished
Exit status code must be 0 ~ 255

Write test5.sh script

#!/bin/bash

function db1 {
    read -p "Enter a value: " value
    echo "doubling the value"
    return $[ $value * 2 ]
}

db1
echo "The new value is $?"

17.2.3 using function output

You can save the output of a function to a variable

Write test5b.sh script

#!/bin/bash

function db1 {
    read -p "Enter a value: " value
    echo $[ $value *2 ]
}

result=$(db1)
echo "The new value is $result"

17.3 using variables in functions

17.3.1 passing parameters to a function

Functions can use standard parameter environment variables to represent the parameters uploaded to functions from the command line.
For example, the function name will be defined in the $0 variable, and any parameter on the function command line will be defined through $1, $2, etc.
You can also use the special variable $# to determine the number of parameters passed to the function.

When you specify a function in a script, you must put parameters and functions on the same line

Write test6.sh script

#!/bin/bash

function addem {
    if [ $# -eq 0 ] || [ $# -gt 2 ]
    then
        echo -1
    elif [ $# -eq 1 ]
    then
        echo $[ $1 + $1 ]
    else
        echo $[ $1 + $2 ]
    fi
}

echo -n "Adding 10 and 15:"
value=$(addem 10 15)
echo $value
echo -n "Let's try adding just one number:"
value=$(addem 10)
echo $value
echo -n "Now trying adding no numbers:"
value=$(addem)
echo $value
echo -n "Finally, try adding three numbers:"
value=$(addem 10 15 200)
echo $value

Pass the variable passed to the script to the function

Write test7.sh script

#!/bin/bash

function func7 {
    echo $[ $1 * $2 ]
}

if [ $# -eq 2 ]
then
    value=$(func7 $1 $2)
    echo "The result is $value"
else
    echo "Usage: test7 a b"
fi

17.3.2 handling variables in functions

1. Global variables

Global variables are variables that are valid anywhere in a shell script.
If you define a global variable in the main part of the script, you can read its value in the function.
If you define a global variable in a function, you can read its value in the topic section of the script.
By default, any variable defined in the script is a global variable, and variables defined outside the function can be accessed inside the function.

Write test8.sh script

#!/bin/bash

function db1 {
    value=$[ $value * 2 ]
}

read -p "Enter a value: " value
db1
echo "The new value is: $value"

2. Local variables

Without using global variables in a function, any variables used inside a function can be declared as local variables.
Add the local keyword before the variable declaration.
You can also use the local keyword in variable assignment statements.

Write test9.sh script

#!/bin/bash

function func1 {
    local temp=$[ $value + 5 ]
    result=$[ $temp * 2 ]
}

temp=4
value=6

func1
echo "The result is $result"
if [ $temp -gt $value ]
then
    echo "temp is larger"
else
    echo "temp is smaller"
fi

17.4 array variables and functions

17.4.1 passing array parameters to functions

Decomposes the values of an array into individual values, which are used as function parameters

Write test10.sh script

#!/bin/bash

function testit {
    local newarray
    newarray=([email protected])
    echo "The new array value is: ${newarray[*]}"
}

myarray=(1 2 3 4 5)
echo "The original array is ${myarray[*]}"
testit ${myarray[*]}

Write test11.sh script

#!/bin/bash

function addarray {
    local sum=0
    local newarray
    newarray=($(echo "[email protected]"))
    for value in ${newarray[*]}
    do
        sum=$[ $sum + $value ]
    done
    echo $sum
}

myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=$(addarray $arg1)
echo "The result is $result"

17.4.2 returning an array from a function

Returns an array variable from a function to a shell script

Writing test12.sh script

#!/bin/bash

function arraydb1r {
    local origarray
    local newarray
    local elements
    local i
    origarray=($(echo "[email protected]"))
    newarray=($(echo "[email protected]"))
    elements=$[ $# -1 ]
    for (( i = 0; i<= $elements; i++ ))
    {
        newarray[$i]=$[ ${origarray[$i]} * 2 ]
    }
    echo ${newarray[*]}
}

myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=($(arraydb1r $arg1))
echo "The new array is: ${result[*]}"

17.5 function recursion

Using recursion to calculate factorial

Write test13.sh script

#!/bin/bash

function factorial {
    if [ $1 -eq 1 ]
    then
        echo 1
    else
        local temp=$[ $1 -1 ]
        local result=$(factorial $temp)
        echo $[ $result * $1 ]
    fi
}

read -p "Enter value: " value
result=$(factorial $value)
echo "The factorial of $value is: $result"

17.6 creating Libraries

If multiple scripts need to use the same piece of code, you can use a function library file, and then reference the library file in multiple scripts

1. Create a library file

Write myfuncs file

function addem {
    echo $[ $1 + $2 ]
}

function multem {
    echo $[ $1 * $2 ]
}

function divem {
    if [ $2 -ne 0 ]
    then
        echo $[ $1 / $2 ]
    else
        echo -1
    fi
}

2. Use this library file

Writing test14.sh script

#!/bin/bash
. ./myfuncs

value1=10
value2=5
result1=$(addem $value1 $value2)
result2=$(multem $value1 $value2)
result3=$(divem $value1 $value2)
echo "The result of adding them is: $result1"
echo "The result of multiplying them is: $result2"
echo "The result of dividing them is: $result3"

17.7 using functions on the command line

17.7.1 creating functions on the command line

Because the shell will interpret the user’s input commands, you can define a function directly on the command line

Carry out the order

function divem { echo $[ $1 / $2 ]; }
divem 100 5

Warning: be careful when creating functions on the command line. If you give a function the same name as a built-in command or another command, the function will override the original command.

17.7.2 define functions in. Bashrc file

1. Directly define functions

Functions can be defined directly in the. Bashrc file in the home directory

If you add

function addem {
    echo $[ $1 + $2 ]
}

2. Read function file

You can use the source command (the dot operator) to add functions from the library file to the. Bashrc script

If you add

. /home/zc/libraries/myfuncs

17.8 examples

The application of functions is not limited to creating their own functions for self entertainment. In the open source world, shared code is the key, and the same applies to script functions. Here we will explain how to download, install and use the GNU shtool shell script library.

17.8.1 download and installation

Download address: ftp://ftp.gnu.org/gnu/shtool/shtool-2.0.8.tar.gz
Decompression file: tar – zxvf shtool-2.0.8.tar.gz

17.8.2 building database

Shtool files must be configured for a specific linux environment
Configuration work must use standard configure and make commands, which are usually used in C programming environment

Execute the order

./configure
make
sudo make install

17.8.3 shtool function library

Shtool library provides a large number of convenient functions for shell scripts

Shtool library function

Functions: description
ARX: creating archives (including some extended functions)
Echo: displays strings and provides some extensions
Fix perm: change the file permissions in the directory tree
Install: install scripts or files
Mdate: displays the modification time of the file or directory
MKDIR: create one or more directories
Mkln: creating links using relative paths
Mkshadow: create a shadow tree
Move: file move with replace function
Path: handler path
Platform: display platform identification
Prop: displays an animated progress bar
Rotate: transpose log file
SCPP: shared C preprocessor
SLO: separate linker options according to the category of the library
Subst: substitution operation using sed
Table: displays the field separated data in the form of a table
Tarball: create tar files from files and directories
Version: creates a version information file

The usage format of shtool function

shtool [options] [function [options] [args]]

17.8.4 usage Library

You can use the shtool function directly from the command line or your own shell script

Write test16.sh script

#!/bin/bash

shtool platform

17.9 summary

Shell script functions allow you to put code used in multiple places in a script in one place. You can create a function that contains the code block, and then use the function name to refer to the code in the script instead of writing that code over and over again.