Shell programming-function call

                            Function call

1. Function definition and call

1.1 Definition method 1

#! /bin/bash
#function define and call  usage instance

print_func()
{
    echo "print_func..."
    echo "\$0:$0..."
    echo "\$1:$1..."
    echo "\$2:$2..."
}


init_func()
{
    echo "init_func..."
    echo "$0"
    echo "$1"
    echo "$2"
    return $?
}

echo call function
print_func

echo call function
init_func "par1" "par2"
init_func 1 2

  

Note: The function generally returns $? to the caller.

1.2 Definition 2

#! /bin/bash
#function define and call  usage instance

function sum()
{
    let y=$1+$2
    echo $y
    return $?
}
echo "Welcome to shell script programming..."
#delay 1 second
sleep 1

sum_value=$(sum 1 2)

echo "sum value is :"$sum_value""

if [ "$sum_value" -gt 0 ];then
    echo "sum_value="$sum_value""
fi

echo "value of y is : $y"

echo "========================"

sum 2 3
echo "value of y is : $y"

Note: through function indicates that the function is defined

2. Precautions for function call

#! /bin/bash
#function define and call  usage instance

sum()
{
    let y=$1+$2
    echo "$y"
    return $?
}
echo "Welcome to shell script programming..."
#delay 1 second
sleep 1

sum_value=$(sum 1 2)

echo "sum value is :$sum_value"

if [ $sum_value -gt 0 ]
then
    echo "sum_value=$sum_value"
fi

echo "============================"
sum 1 2

echo "############################"
$(sum 4 5)

note:

  1. Use the $() method to call the function, the internal echo command will not be output to the standard output;
  2. Called in the $() method, it must be received by a variable, otherwise an error will be reported;
  3. echo? The return value is the echo output value of the function immediately following the return statement.

3. Differences in function call methods

#! /bin/bash
#function define and call  usage instance

sum()
{
    let y=$1+$2
    echo $y
    return $?
}
echo "Welcome to shell script programming..."
#delay 1 second
sleep 1

sum_value=$(sum 1 2)

echo "sum value is :"$sum_value""

if [ "$sum_value" -gt 0 ];then
    echo "sum_value="$sum_value""
fi

echo "value of y is : $y"

echo "========================"

sum 2 3
echo "value of y is : $y"

Guess you like

Origin blog.csdn.net/yanlaifan/article/details/114553682