shell编程高级之函数
来源:互联网 发布:标致pp2000软件下载 编辑:程序博客网 时间:2024/05/21 22:32
shell编程高级之函数
创建函数
#第一种方式function name {
commands
}
#第二种方式name(){
commands
}#使用函数
#!/bin/bash
#function
# 此处fun1和{中间要有空格
function fun1 {
echo "i am fun1"
}
fun1
fun2(){
echo "i am fun2"
}
fun2函数返回值
#默认退出状态码 $?
#return命令
#函数已结束就取返回值
#退出状态码必须在0-255之间
function fun1 {
commands
return 250
}
fun1
echo $?
#使用函数输出function fun1 {
commands
echo "holy shit"
}
val=`fun1`
echo $val在函数中使用变量
# 向函数中传递参数
# 需在同一行
#在函数中处理变量
#在函数外定义的都是全局变量
#在函数内部使用局部变量加local关键字
# $0 函数名 $1 $2 $… 参数值 $# 计数fun5(){
if [ $# -eq 0 ] || [ $# -gt 2 ]
then
echo -1
elif [ $# -eq 1 ]
then
echo $[$1 * $1]
else
echo $[$1 * $2]
fi
}
fun5 10
fun5 10 11
fun5 10 11 12- 数组变量和函数
#传递给函数数组变量
#在传递给函数前分解成单个值,传递后在函数内部组合成数组function testit {
local newarray
newarray=(`echo "$@"`)
echo "The new array value is : ${newarray[*]}"
}
myarray=(1 2 3 4 5)
echo "The original array value is : ${myarray[*]}"
testit ${myarray[*]}
#让函数返回数组变量
rtarray(){
local originalArr
local newArr
local elements
local i
originalArr=(`echo "$@"`)
newArr=(`echo "$@"`)
elements=$[ $#-1 ]
for(( i = 0;i <= $elements;i++ ))
{
newArr[$i]=$[${originalArr[$i]}*2]
}
echo ${newArr[*]}
}
myarr=(1 2 3 4 5)
echo "The original array value is :${myarr[*]}"
val1=`rtarray ${myarr[*]} `
echo "The new array value is : ${val1[*]}" - 函数递归
#计算阶乘
factorial(){
if [ $1 -eq 1 ]
then
echo 1
else
local tmp=$[$1-1]
local result=`factorial $tmp`
echo $[ $result * $1 ]
fi
}
read -p "Enter The Value:" value
result=`factorial $value`
echo "The factorial of the $value is $result" - 创建库
#引入. ./ku.sh
.号为source的快捷别名.称作点操作符. ./ku.sh
result=`addem 10 15`
echo "The result is $result"
- shell编程高级之函数
- linux shell高级脚本编程之函数篇
- 高级shell脚本编程之重定向、环境变量、shell函数、echo命令用法
- Shell编程之 函数
- shell 编程之函数
- UNIX高级编程之简易版shell
- shell编程高级之sed编辑器
- shell编程高级之gawk程序
- shell编程高级之正则表达式
- Shell编程之函数笔记
- shell编程之函数基础
- shell编程之函数基础
- Shell脚本编程之函数
- shell编程之函数浅析
- shell 脚本编程之函数
- 函数式编程之高级函数
- 高级shell编程技巧
- shell脚本高级编程
- Failed to load JavaHL Library解决方法
- LeetCode 67 : Add Binary (Java)
- 使用Elasticsearch,Kafka和Cassandra构建流式数据中心
- Android 让EditText输入框失去焦点
- CentOS6.6系统下以RPM方式安装mysql-5.7.9
- shell编程高级之函数
- ArrayBlockingQueue阻塞队列的使用示例
- 分布式数据重复提交
- python: error while loading shared libraries: libpython3.4m.so.1.0: cannot open shared object file:
- Linux -----oops错误
- ubuntu14.04密码正确,进入不了图形界面
- 【Unity开发】简单的对象池实现
- leetcode -- Plus One--与add binary类似--要了解
- (一)使用RED5搭建流媒体服务器