0 Structured programming, cannot run independently, execute when it needs to be called, can be called multiple times,
Calling a function:
Just use the function name directly.
1 Definition:
Way 1: function FUNCNAME { command } Way 2: FUNCNAME() { command }
2 Custom function return value:
return #The
return value is between 0-255, as long as return, the function will exit
The difference from $?:
The return value of $? depends on the execution result of the last command in the script. If you define a function, various errors are reported in the function, but the last line echo 11, then the result returned by echo $? must be 0.
And return # is a custom return value.
3 cases:
eg1: #!/bin/bash # TWOSUM() { echo ${$1+$2} } SUM=`TWOSUM 1 2` pass parameters to the function and execute echo $SUM eg2: #!/bin/bash # ADDUSER() { USERNAME=hadoop if !id -u $USERNAME &> /dev/null; then useradd $USERNAME echo $USERNAME | passwd --stdin $USERNAME &> /dev/null return 0 defines the return value of the function else return 1 be } ADDUSER calls this function if [$? -eq 0]; then output the status bits of the previous line of execution echo "add user finished" else echo "failuer" be eg3: #!/bin/bash # ADDUSER() { USERNAME=$1 if !id -u $USERNAME &> /dev/null; then useradd $USERNAME echo $USERNAME | passwd --stdin $USERNAME &> /dev/null return 0 else return 1 be } for I in {1..10}; do ADDUSER user$I if [$? -eq 0]; then echo "add user$I finished" else echo "add user$I failuer" be done