1.函数

函数是一个脚本代码块,你可以为其命名并在代码中任何位置重用。要在脚本中使用该代码块时,只要使用所起的函数名就行了(这个过程称为调用函数)。本节将会介绍如何在shell脚本中创建和使用函数

创建函数

function name {
commands
}
name() {
commands
}

使用函数

[root@localhost advanced_shell_script]# cat test1.sh
#!/bin/bash
#using a function in a script function func1 { echo "This is an example of a function" } count= while [ $count -le ] ;do
func1
count=$[ $count + ]
done echo "This is the end of the loop"
func1
echo "This is script end" [root@localhost advanced_shell_script]# ./test1.sh
This is an example of a function
This is an example of a function
This is an example of a function
This is the end of the loop
This is an example of a function
This is script end
[root@localhost advanced_shell_script]#

使用return  返回 函数

[root@localhost advanced_shell_script]# cat test2.sh
#!/bin/bash #using the return command in a function function db1 {
read -p "Enter a value:" value
echo "doubling the value"
return $[ $value * ] }
db1
echo "The new value $?" [root@localhost advanced_shell_script]# ./test2.sh
Enter a value:
doubling the value
The new value 4
[root@localhost advanced_shell_script]# ./test2.sh #注意$? 返回函数值必须小于256 ,因此需要另外一种方法
Enter a value:200
doubling the value
The new value 144
[root@localhost advanced_shell_script]#

另外一种方法

[root@localhost advanced_shell_script]# cat test3.sh
#!/bin/bash #using the return command in a function function db1 {
read -p "Enter a value:" value
#echo "doubling the value"
echo $[ $value * 2 ] #新函数会用echo语句来显示计算的结果。该脚本会获取dbl函数的输出,而不是查看退出状态码
}
value1=$(db1)
echo "The new value $value1" [root@localhost advanced_shell_script]# ./test3.sh
Enter a value:
The new value
[root@localhost advanced_shell_script]#

传递参数:

[root@localhost advanced_shell_script]# cat test4.sh
#!/bin/bash
#passing parameters to a function function addem {
if [ $# -eq ] || [ $# -gt ];then
echo -
elif [ $# -eq ];then
echo $[ $ * $ ]
else
echo $[ $ + $ ] fi
}
echo -n "Adding 20 and 30:"
value=$(addem )
echo $value echo -n "30 *:"
value=$( addem )
echo $value echo -n "10 20 30:"
value=$(addem )
echo $value [root@localhost advanced_shell_script]# ./test4.sh
Adding and :
*:
:-
[root@localhost advanced_shell_script]#

命令行传递参数

[root@localhost advanced_shell_script]# cat test5.sh
#/bin/bash
#trying to access script parameters inside a function function func1 {
echo $[ $ * $ ] } if [ $# -eq ];then value=$(func1 $ $)
echo "The result is $value"
else
echo "Usage:badtest1 a b"
fi
[root@localhost advanced_shell_script]# ./test5.sh
Usage:badtest1 a b
[root@localhost advanced_shell_script]# ./test5.sh
The result is
[root@localhost advanced_shell_script]#

在函数中处理变量

全局变量和局部变量

. 全局变量
全局变量是在shell脚本中任何地方都有效的变量。如果你在脚本的主体部分定义了一个全局变量,那么可以在函数内读取它的值。类似地,如果你在函数内定义了一个全局变量,可以在脚本的主体部分读取它的值。
 . 局部变量
无需在函数中使用全局变量,函数内部使用的任何变量都可以被声明成局部变量。要实现这一点,只要在变量声明的前面加上local关键字就可以了。
[root@localhost advanced_shell_script]# cat test6.sh
#!/bin/bash
#demonstrating the local keyword
function func1 { local test1=$[ $test2 * 2 ] test3=$[ test2 * ] }
test3=
test1=
test2=
func1
echo "$test1 $test2 $test3 " [root@localhost advanced_shell_script]# vim test6.sh
[root@localhost advanced_shell_script]# ./test6.sh #局部变量的值 test1 在函数执行后没有被修改,test3 的值在函数执行后,被修改为函数执行的结果
1223340 5 10
[root@localhost advanced_shell_script]#

向函数传递数组变量的注意事项

[root@localhost advanced_shell_script]# cat test8.sh
#!/bin/bash
# array variable to function test
function test1 { #在向函数传递数组变量的时候,需要将数据变量当做一个整体进行传递,通过$@ 方式
                    #$@ 将给定的多个参数定义为同一字符串的多个单独的单词,类似  "A" "B"  "C"
local newarray
newarray=($(echo $@))
echo "The new array value is: ${newarray[*]}"
}
function test2 { #在向函数传递数组变量时,如果使用 $1 参数,会识别为数组变量的第一个参数。无法完整的传递整个参数。默认不会将传递给函数的数组变量看成一个参数
local newarray
newarray=$
echo "The test2 function valueis: ${newarray[*]}" } myarray=( )
echo "The original array is ${myarray[*]}"
test1 ${myarray[*]}
test2 ${myarray[*]} [root@localhost advanced_shell_script]# ./test8.sh
The original array is
The new array value is:
The test2 function valueis:
[root@localhost advanced_shell_script]#

函数递归的使用,使用bash -x 跟踪递归的处理步骤很有效

root@localhost advanced_shell_script]# cat test11.sh
#!/bin/bash
#using recursion function factorial { if [ $ -eq ];then echo
else
local temp=$[ $ - ]
local result=`factorial $temp`
#return $
echo $[ $result * $ ]
fi
} value=
result=$(factorial $value)
echo "$result"
[root@localhost advanced_shell_script]# bash -x test11.sh
+ value=
++ factorial
++ '[' -eq ']'
++ local temp=
+++ factorial
+++ '[' -eq ']'
+++ local temp=
++++ factorial
++++ '[' -eq ']'
++++ local temp=
+++++ factorial
+++++ '[' -eq ']'
+++++ local temp=
++++++ factorial
++++++ '[' -eq ']'
++++++ echo
+++++ local result=
+++++ echo
++++ local result=
++++ echo
+++ local result=
+++ echo
++ local result=
++ echo
+ result=
+ echo [root@localhost advanced_shell_script]#

创建库的办法

[root@localhost advanced_shell_script]# cat myfuncs   #创建的库文件需要有执行权限
#my script functions function addem { echo $[ $ + $ ] } function multem { echo $[ $ * $ ]
} function divem { if [ $ -ne ];then echo $[ $ / $ ] else
echo
fi
} [root@localhost advanced_shell_script]# cat test12.sh
#!/bin/bash
# using functions defined in a library file
source ./myfuncs #两种方式调用库文件 ,source 和 .. ,这是让库文件在当前shell 调用。如果使用 ./mufuncs 相当于在子shell 调用了。会找不到命令
# ../myfuncs
value1=
value2=
result1=$(addem $value1 $value2)
result2=$(multem $value1 $value2)
result3=$(divem $value1 $value2)
echo "The result of adding them is: $result1"
echo "The result of multiplying them is: $result2"
echo "The result of dividing them is: $result3"
#
[root@localhost advanced_shell_script]# ./test12.sh
The result of adding them is:
The result of multiplying them is:
The result of dividing them is:
[root@localhost advanced_shell_script]#

在命令行创建函数:

[root@localhost advanced_shell_script]# function funcs {  #当在命令行上定义函数时,你必须记得在每个命令后面加个分号,这样shell就能知道在哪里是命令的起止了
> echo $[ $ + $  ];}
[root@localhost advanced_shell_script]# funcs [root@localhost advanced_shell_script]#

在 .bashrc 中定义函数

[root@localhost ~]# cat /root/.bashrc     # .bashrc 是函数的最佳定义位置
# .bashrc # User specific aliases and functions alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i' # Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi function add {
echo $[ $ + $ ] }
[root@localhost ~]#

在script 中使用在.bashrc 中定义的函数

root@localhost advanced_shell_script]# cat test13.sh
#!/bin/bash source /root/.bashrc #通过source 命令将函数调用进来,否则命令找不到 result=$(add )
echo "$result" [root@localhost advanced_shell_script]#

高级shell 脚本的更多相关文章

  1. Linux&shell之高级Shell脚本编程-创建函数

    写在前面:案例.常用.归类.解释说明.(By Jim) 使用函数 #!/bin/bash # testing the script function myfun { echo "This i ...

  2. 《Linux命令行与shell脚本编程大全 第3版》高级Shell脚本编程---47

    以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下:

  3. Linux&shell之高级Shell脚本编程-创建菜单

    写在前面:案例.常用.归类.解释说明.(By Jim) 创建菜单#!/bin/bash# testing the scriptclearechoecho -e "\t\t\tSys Admi ...

  4. 《Linux命令行与shell脚本编程大全 第3版》

    第一部分 Linux 命令行 第1章  初识Linux she1.1   什么是Linux 21.1.1 深入探究Linux 内核 31.1.2 GNU 工具 61.1.3 Linux 桌面环境 81 ...

  5. shell脚本-高级变量

    shell脚本-高级变量 字符串变量切片 ${#var}: 返回字符串变量var的长度 ${var:offset}: 返回字符串变量var中从第offset个字符后(不包括第offset 个字符)的字 ...

  6. 一、Shell脚本高级编程实战第一部

    Shell脚本语言是实现linux系统自动化管理的重要且必要的工具,几乎每一个合格的linux系统管理员或者高级运维工程师都要熟练shell脚本语言的编写,只有这样才能提升工作效率,解决工作中的重复劳 ...

  7. Linux Shell 高级编程技巧4----几个常用的shell脚本例子

    4.几个常用的shell脚本例子    4.0.在写脚本(同样适用在编程的时候),最好写好完善的注释    4.1.kill_processes.sh(一个杀死进程的脚本) #!/bin/bash c ...

  8. 四、Shell脚本高级编程实战第四部

    一.比较两个数的大小 #!/bin/shread -p "Pls input two num:" a b[ -z "$a" ] || [ -z "$b ...

  9. 三、Shell脚本高级编程实战第三部

    保养好自己的发动机:身体的和心里的身体健康:打打球,跑跑步心里健康:多和大家接触,保持家人.朋友的良好关系一.$*和$@的区别   $*:获取shell的所有参数,将所有的参数视为单个字符串.   $ ...

随机推荐

  1. CS(计算机科学)知识体

    附 录 A                   CS( 计算机科学)知识体 计算教程 2001 报告的这篇附录定义了计算机科学本科教学计划中可能讲授的知识领域.该分类方案的依据及其历史.结构和应用的其 ...

  2. 64bit program invoke 32bit library with rpcgen

    https://www.cnblogs.com/ddk3000/p/5051108.html 这篇博客介绍了一种用rpc的方法实现64位程序调用32位动态库的方法,核心是利用rpcgen简化了进程间通 ...

  3. burp抓取ios设备https数据包

    参考了网上其他相关教程,自己动手试了一次,有效的方法可确定为: 1.让PC机和移动端处于同一局域网, 2.burp设定监听所有接口,并监听一个端口 3.手机端设置代理,方式为手动,ip地址填PC在局域 ...

  4. linux-rhel7配置网卡bond双网卡主备模式

    参考以下文章中的 2.centos7配置bonding: https://www.cnblogs.com/huangweimin/articles/6527058.html 以下是配置过程的操作和打印 ...

  5. Flask 接入第三方云通讯平台时出现 {‘172001’:’网络错误’}

    错误:{‘172001’:’网络错误’},经过上网查找原因,原来是 Python 升级到 2.7.9 之后引入了一个新特性,当打开一个 https 链接时,会验证一次 SSL 证书.而当目标网站使用的 ...

  6. esp32驱动SSD1306的oled显示汉字(micropython)

    1.完整源码: 主函数oled.py from ssd1306 import SSD1306_SPI from ssd1306 import SSD1306 import font import ma ...

  7. 洛谷P4051 字符加密 [JSOI2007] SA

    正解:SA 解题报告: 传送门! 和工艺那题有点儿像鸭,,,反正肯定就都想到倍长然后SA拍个序嘛先 然后就做完了,,,我发现SA的题刷起来特别susi,,,基本上紫题级别的都just一个模板就欧克了最 ...

  8. SharePoint 2010 查看dll的PublicKeyToken值方法

    在做asp.net开发过程中,偶尔对有些dll,进行强制签名,那么在注册dll到gac的时候,就需要知道dll的PublicKeyToken值,如何通过简单的方法,来获得这个值呢,下面是一个很好又实用 ...

  9. 关于 RESTful API 中 HTTP 状态码的定义

    最近正好使用了一会儿 Koa ,在这说一下自己对各个 请求码的见解和使用场景,懒人直接看 200.400.401.403.404.500 就可以了. 其中 2XX/3XX 其实都是请求成功,但是结果不 ...

  10. requests 获取百度推广信息

    2019年的第一篇博客,恩,好久没写过博客了,恩,忘了,哈哈,实在是太懒了 今天写一个爬取百度推广数据的爬虫,当然我写的肯定不是那么的完美,但是能用,大哭 注意:有的时候,get或post方法获取数据 ...