This is the 9th day of my participation in Gwen Challenge

Sometimes in our program, a piece of code will be reused, if it is written again, it is not only a waste of time, but also meaningless, then we can use the function to reuse the code, the use of this function can be used.

function

The function modularizes the function to be realized, which makes the code structure and program workflow clearer, and also improves the readability and reusability of the program

# Way 1 omit ()
functionThe function name {There must be a space between the function name and {Code [return int]
}
# FunctionFunction name () {}Copy the code
  • In the absence of a return statement, the function returns the execution result of the last command in the code segment
  • After a function is defined, it needs to be called

example

#! /bin/sh
# define function
function hello {      # omitted ()
        echo "hello function"
}
# main executes the code
hello   # function call
exit 0
Copy the code
[root@localhost sh]# sh function.sh 
hello function
Copy the code

Function call parameters

Function name Parameter 1 Parameter 2......

Arguments can be passed into a script by passing in a location variable at the time of a function call

Functions of Shell scripts do not have argument lists, but they can also be passed parameters through environment variables.

Position variables in functions do not conflict with position variables in scripts

Position variables in a function are passed in at the function call, and position variables in a script are passed in at script execution.

#! /bin/sh
_choice() {echo "your choice is The $1" # position variable
}
#main
case The $1 in
        c++)_choice c++;;   # function calls pass in position variable c++
        java)_choice java;;
        *)echo "$0:please select in(c++/java)"
esac
exit 0

[root@localhost sh]# sh function_parmes.sh 
function_parmes.sh:please select in(c++/java)
[root@localhost sh]# sh function_parmes.sh java
your choice is java
Copy the code

Variables in a function

  • Variables defined in functions are global
#! /bin/sh
function fun(){
	a=10
	echo "fun:a=$a"
}
a=5
echo "main:a=$a"
fun				# function call
echo "main:a=$a"
exit 0
# Execution result
main:a=5
fun:a=10
main:a=10
Copy the code
A local variable
  • Add the local keyword to declare variables as local variables
#! /bin/sh
function fun() {local a=10  # local variables
    echo "fun:a=$a"
}
a=5
echo "main:a=$a"
fun             # function call
echo "main:a=$a"
exit 0
Copy the code

The execution result

# Execution result
main:a=5
fun:a=10
main:a=5
Copy the code