1、函数基本格式
function 函数名 { 命令 }
注:function可以省略
2、函数实例应用
1)创建函数文件
[root@localhost xxx]# cat functions.main #!/bin/bash findit() { if [ $# -lt 1 ];then echo "Usage:findit file" return 1 fi find /home -name $1 -print }
2)定位文件
[root@localhost xxx]# . /home/xxx/functions.main
此即<点> <空格> <斜线> <文件名>
3)set ##检查载入函数4)findit 文件名 ##执行载入函数
5)unset findit ##删除shell函数
eg1:利用函数处理输入的名字,名字只能包含大小字母,其它为非法字符。如果输入非法字符则提示,直到输入正确为止。
#!/bin/bash function char_name () { _LETTER_ONLY=$1 _LETTER_ONLY=`echo $1|awk '{if($0~/[^a-z A-Z]/)print "1"}'` if [ "$_LETTER_ONLY" != "" ];then return 1 else return 0 fi } function error_name () { echo "$@ contains error,it must contain only letters" } while : do echo -n "Please enter your first name:" read F_NAME if char_name $F_NAME ;then break else error_name $F_NAME fi done while : do echo -n "Please enter your last name:" read L_NAME if char_name $L_NAME ;then break else error_name $L_NAME fi done
eg2:列出file.txt文本文件行号
[root@localhost xxxxx]# cat file.txt Filesystem Size Used Avail Use% Mounted on /dev/mapper/rhel-root 37G 3.2G 34G 9% / devtmpfs 897M 0 897M 0% /dev tmpfs 912M 0 912M 0% /dev/shm tmpfs 912M 9.0M 903M 1% /run tmpfs 912M 0 912M 0% /sys/fs/cgroup /dev/sda1 1014M 179M 836M 18% /boot tmpfs 183M 28K 183M 1% /run/user/0 /dev/sr0 3.8G 3.8G 0 100% /run/media/root/RHEL-7.4 Server.x86_64 [root@localhost xxxxx]# vi number_file.sh #!/bin/bash function file_number () { _FILE_NAME=$1 if [ $# -ne 1 ]; then echo "file_number:I need a filename to number" fi loop=1 while read line do echo "$loop:$line" loop=`expr $loop + 1` done <$_FILE_NAME } [root@localhost xxxxx]# . /home/xxxxx/number_file.sh [root@localhost xxxxx]# file_number file.txt 1:Filesystem Size Used Avail Use% Mounted on 2:/dev/mapper/rhel-root 37G 3.2G 34G 9% / 3:devtmpfs 897M 0 897M 0% /dev 4:tmpfs 912M 0 912M 0% /dev/shm 5:tmpfs 912M 9.0M 903M 1% /run 6:tmpfs 912M 0 912M 0% /sys/fs/cgroup 7:/dev/sda1 1014M 179M 836M 18% /boot 8:tmpfs 183M 28K 183M 1% /run/user/0 9:/dev/sr0 3.8G 3.8G 0 100% /run/media/root/RHEL-7.4 Server.x86_64
eg3:字符大小写转换
#!/bin/bash function str_to_upper () { if [ $# -ne 1 ]; then echo "Please enter letters!" return 1 fi echo $@|tr [a-z] [A-Z] }
特别说明:本文是学习David Tansley 《 Linux and UNIX Shell Programming》实体书之后整理的,因本站必需填写url,文章类型写成了原创。在此分享,以供大家一起学习。如有不良影响,请联系本人删除。