您现在的位置是:网站首页> 编程资料编程资料
Shell脚本中使用function(函数)示例_linux shell_
2023-12-09
216人已围观
简介 Shell脚本中使用function(函数)示例_linux shell_
函数可以在shell script当中做一个类似自定义执行命令,最大的功能就是可以简化我们很多的程序代码。需要注意的是shell script的执行方式是由上而下/由左而右,因此在shellscript当中的function的设置一定要在程序的最前面,这样才能够在执行时被找到可用的程序段。
复制代码 代码如下:
#!/bin/bash
# Program
# This program is to show the use of "function"
# History
# 2013/5/4 by Lvcy First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/loacl/sbin:~/bin
export PATH
#输出统一信息
function printInfo ()
{
echo -n "Your choice is "
}
#将小写字符转换为大写字符
function dotr()
{
tr 'a-z' 'A-Z'
}
read -p "Please input your choice(one|two|three|four):" num
#用case做条件判断
case $num in
"one")
printInfo; echo $num | dotr
;;
"two")
printInfo; echo $num | dotr
;;
"Three")
printInfo; echo $num | dotr
;;
"four") printInfo; echo $num | dotr
;;
esac
exit 0
下面是一个一般的带有function函数的shell脚本:
复制代码 代码如下:
#!/bin/bash
# Program
# This program is show the params of function
# History
# 2013/5/14 by Lvcy First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
function printInfo()
{
echo "Your choice is $1"
}
case $1 in
"one")
printInfo 1
;;
"two")
printInfo 2
;;
"three")
printInfo 3
;;
"four")
printInfo 4
;;
esac
exit 0
若以上文件名为sh02.sh,则执行这个script的命令为:
复制代码 代码如下:
sh sh02.sh one
相关内容
- Shell脚本中让进程休眠的方法(sleep用法)_linux shell_
- Shell脚本中执行sql语句操作mysql的5种方法_linux shell_
- Shell实现系统时间和BIOS时间同步校准脚本分享_linux shell_
- Python使用淘宝API查询IP归属地功能分享_linux shell_
- golang如何用type-switch判断interface变量的实际存储类型_Golang_
- 莽荒纪战力提升小技巧有哪些_手机游戏_游戏攻略_
- 莽荒纪实战顶级阵容有哪些_手机游戏_游戏攻略_
- 刀塔传奇平民非R远征通关搭配推荐_手机游戏_游戏攻略_
- 城堡争霸怪物攻城d5布局攻略 怪物攻城布局阵法介绍 _手机游戏_游戏攻略_
- 刀塔传奇远征通关赚钱英雄搭配攻略_手机游戏_游戏攻略_