Shell 函数

shell 函数

语法

1
2
3
function_name () { 
list of commands
}

示例

1
2
3
4
5
6
7
8
9
#!/bin/sh

# Define your function here
Hello () {
echo "Hello World"
}

# Invoke your function
Hello

函数传参

函数传参类似于脚本传参$1, $2..$n

1
2
3
4
5
6
7
8
9
#!/bin/sh

# Define your function here
Hello () {
echo "Hello World $1 $2"
}

# Invoke your function
Hello Zara Ali

返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/sh

# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}

# Invoke your function
Hello Zara Ali

# Capture value returnd by last command
ret=$?

echo "Return value is $ret"

函数嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#!/bin/sh

# Calling one function from another
number_one () {
echo "This is the first function speaking..."
number_two
}

number_two () {
echo "This is now the second function speaking..."
}

# Calling function one.
number_one


Shell 函数
https://yxibng.github.io/2022/02/25/Shell/2022-02-25-shell 函数/
作者
yxibng
发布于
2022年2月25日
许可协议