学习python风格, 优雅规范书写shell代码
定义格式:
[function] foo() {
COMMANDS
[return N] # 返回码(N)的取值范围: 0~255
}
调用格式:
foo [ARGS]
实例:
# Defined function
function hello() {
echo "Hello World !"
}
# Invoke function
hello
实例:
function two_num_sum() {
let sum=$1+$2
return ${sum}
}
read -p "Please input the first number: " arg1
read -p "Please input the second number: " arg2
two_num_sum ${arg1} ${arg2}
ret=$?
echo "The sum of two numbers is ${ret}"
和其他语言一样, Shell也可以包含外部脚本. 这样可以很方便的封装一些公用的代码作为一个独立的文件.
实例:
functions.sh文件:
function hello() {
echo "Hello World !"
}
function two_num_sum() {
let sum=$1+$2
return ${sum}
}
bin.sh文件:
#!/bin/bash
#####################################
# @Author:
# @Created Time: 2019-10-01 02:07:32
# @Description:
#####################################
source ./functions.sh
hello
read -p "Please input the first number: " arg1
read -p "Please input the second number: " arg2
two_num_sum ${arg1} ${arg2}
ret=$?
echo "The sum of two numbers is ${ret}"
执行bin.sh的结果:
原文:https://www.cnblogs.com/zakzhu/p/11614694.html