一、函数

  1、什么是shell函数

    把相同程序段定义成函数,可以减少整个程序的代码量,提升开发效率

    增加程序的可读性,易读性,提升管理效率

    可以失效程序功能模块化,使程序具备可移植性

    其实linux系统里面近2000个命令可以说都是shell的函数

  2、语法

    function 名称() 复合命令块[重定向]

function 函数名 () {    #function可以忽略不写
指令。。。
return n    #和exit类似,return是退出函数
}

  3、基础实践

    1)开发一个建立两个简单函数并调用执行

[root@web1 scripts]# cat test21.sh
#!/bin/bash
boy(){
echo "i am boy"
}
function girl(){
echo "i am girl"
}
boy
girl
[root@web1 scripts]# ./test21.sh
i am boy
i am girl
[root@web1 scripts]# cat test21-.sh
#!/bin/bash
boy(){
echo "i am boy"
}
function girl(){
echo "i am girl"
}
boy
girl
boy1
[root@web1 scripts]# ./test21-.sh
i am boy
i am girl
./test21-.sh: line : boy1: command not found
[root@web1 scripts]#

  2)分离函数体和执行行数的脚本文件

[root@web1 scripts]# cat >>/etc/init.d/functions<<- EOF
> boy(){
> echo "i am boy"
> }
> EOF
[root@web1 scripts]# !tail
tail - /etc/init.d/functions
boy(){
echo "i am boy"
}
[root@web1 scripts]#
[root@web1 ~]# function boy1 {
> echo "i am boy1"
> }

[root@web1 scripts]# boy1
 i am boy1

  4、实现企业级URL检查脚本

    经函数的传参换成脚本文件命令行传参,判断任意指定的url是否存在移除

    1)实践脚本传参,检查web URL是否正常

[root@web1 scripts]# cat test23.sh
#判断传参格式是否为1
#!/bin/bash if [ $# -en ]
#“$#”获取当前执行的脚本后面接的参数总个数
then
echo $"usage:$0 url"
exit
fi wget --spider -q -o /dev/null --tries= -T $
#T超时实践,这里的$1为脚本的参数
if [ $? -eq ]
#“$?”获取上一个指令的执行状态返回值,0成功,非零失败
then
echo "$1 is yes"
else
echo "$1 is no"
fi

    2)将上述检测的功能写成函数,并将函数传参转换成脚本命令行传参,判断任意指定的URL是否存在异常

#!/bin/bash
function usage(){
echo $"usage:$0 url"
exit
} function check_url(){ #检测URL函数
wget --spider -q -o /dev/full --tries= -T $
#这里$1就是函数传参
if [ $? -eq ]
then
echo "$1 is yes"
else
echo "$1 is no"
fi } function main(){ #主函数
if [ $# -ne ]
#如果传入的是多个参数,则打印帮助函数,提示用户
then
usage
fi
check_url $
}
#接收函数的传参,即把下文main结尾的$*传到这里
main $*
#这里的$*就是把命令行接收的所有参数作为函数参数传给函数内部,是一种常用收发

  运行结果

[root@web1 scripts]# sh test24.sh  www.baidu.com
www.baidu.com is yes
[root@web1 scripts]# sh test24.sh www.baidu1.com
www.baidu1.com is no
[root@web1 scripts]#

  3)将函数的传参转换层脚本文件命令行传参,判断任意指定的url是否存在异常,并以更专业的显示

#!/bin/sh
. /etc/init.d/functions             function usage(){
echo $"usage:$0 url"
exit
} function check_url(){
wget --spider -q -o /dev/null --tries= -T $
if [ $? -eq ]
then
action "$1 is yes." /bin/true      #action 就是调用函数库的函数
else
action "$1 is no." /bin/false
fi
} function main(){
if [ $# -ne ]
then
usage
fi
check_url $
}
main $*

    效果

[root@web1 scripts]# chmod +x test25.sh
[root@web1 scripts]# ./test25.sh www.baidu.com
www.baidu.com is yes. [ OK ]
[root@web1 scripts]# ./test25.sh www.baidu1.com
www.baidu1.com is no. [FAILED]
[root@web1 scripts]#

  5、利用shell函数开发一键优化系统脚本

    centos6

#!/bin/bash
# author:oldboy
# qq:
#set env
export PATH=$PATH:/bin:/sbin:/usr/sbin
# Require root to run this script.
if [ "$UID" != "" ]; then
echo "Please run this script by root."
exit
fi #define cmd var
SERVICE=`which service`
CHKCONFIG=`which chkconfig` function mod_yum(){
#modify yum path
if [ -e /etc/yum.repos.d/CentOS-Base.repo ]
then
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup&&\
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
fi
} function close_selinux(){
#.close selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
#grep SELINUX=disabled /etc/selinux/config
setenforce &>/dev/null
#getenforce
} function close_iptables(){
#.close iptables
/etc/init.d/iptables stop
/etc/init.d/iptables stop
chkconfig iptables off
} function least_service(){
#.least service startup
chkconfig|awk '{print "chkconfig",$1,"off"}'|bash
chkconfig|egrep "crond|sshd|network|rsyslog|sysstat"|awk '{print "chkconfig",$1,"on"}'|bash
#export LANG=en
#chkconfig --list|grep :on
} function adduser(){
#.add oldboy and sudo
if [ `grep -w oldboy /etc/passwd|wc -l` -lt ]
then
useradd oldboy
echo |passwd --stdin oldboy
\cp /etc/sudoers /etc/sudoers.ori
echo "oldboy ALL=(ALL) NOPASSWD: ALL " >>/etc/sudoers
tail - /etc/sudoers
visudo -c &>/dev/null
fi
} function charset(){
#.charset config
cp /etc/sysconfig/i18n /etc/sysconfig/i18n.ori
echo 'LANG="zh_CN.UTF-8"' >/etc/sysconfig/i18n
source /etc/sysconfig/i18n
#echo $LANG
} function time_sync(){
#.time sync.
cron=/var/spool/cron/root
if [ `grep -w "ntpdate" $cron|wc -l` -lt ]
then
echo '#time sync by oldboy at 2010-2-1' >>$cron
echo '*/5 * * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1' >>$cron
crontab -l
fi
} function com_line_set(){
#.command set.
if [ `egrep "TMOUT|HISTSIZE|HISTFILESIZE" /etc/profile|wc -l` -ge ]
then
echo 'export TMOUT=300' >>/etc/profile
echo 'export HISTSIZE=5' >>/etc/profile
echo 'export HISTFILESIZE=5' >>/etc/profile
. /etc/profile
fi
} function open_file_set(){
#.increase open file.
if [ `grep /etc/security/limits.conf|wc -l` -lt ]
then
echo '* - nofile 65535 ' >>/etc/security/limits.conf
tail - /etc/security/limits.conf
fi
} function set_kernel(){
#.kernel set.
if [ `grep kernel_flag /etc/sysctl.conf|wc -l` -lt ]
then
cat >>/etc/sysctl.conf<<EOF
#kernel_flag
net.ipv4.tcp_fin_timeout =
net.ipv4.tcp_tw_reuse =
net.ipv4.tcp_tw_recycle =
net.ipv4.tcp_syncookies =
net.ipv4.tcp_keepalive_time =
net.ipv4.ip_local_port_range =
net.ipv4.tcp_max_syn_backlog =
net.ipv4.tcp_max_tw_buckets =
net.ipv4.route.gc_timeout =
net.ipv4.tcp_syn_retries =
net.ipv4.tcp_synack_retries =
net.core.somaxconn =
net.core.netdev_max_backlog =
net.ipv4.tcp_max_orphans =
net.nf_conntrack_max =
net.netfilter.nf_conntrack_max =
net.netfilter.nf_conntrack_tcp_timeout_established =
net.netfilter.nf_conntrack_tcp_timeout_time_wait =
net.netfilter.nf_conntrack_tcp_timeout_close_wait =
net.netfilter.nf_conntrack_tcp_timeout_fin_wait =
EOF
sysctl -p
fi
}
function init_ssh(){
\cp /etc/ssh/sshd_config /etc/ssh/sshd_config.`date +"%Y-%m-%d_%H-%M-%S"`
#sed -i 's%#Port 22%Port 52113%' /etc/ssh/sshd_config
sed -i 's%#PermitRootLogin yes%PermitRootLogin no%' /etc/ssh/sshd_config
sed -i 's%#PermitEmptyPasswords no%PermitEmptyPasswords no%' /etc/ssh/sshd_config
sed -i 's%#UseDNS yes%UseDNS no%' /etc/ssh/sshd_config
/etc/init.d/sshd reload &>/dev/null
} function update_linux(){
#.upgrade linux.
if [ `rpm -qa lrzsz nmap tree dos2unix nc|wc -l` -le ]
then
yum install lrzsz nmap tree dos2unix nc -y
#yum update -y
fi
}
main(){
mod_yum
close_selinux
close_iptables
least_service
adduser
charset
time_sync
com_line_set
open_file_set
set_kernel
init_ssh
update_linux
}
main

    centos7

    未更新

  6、利用shell函数开发rsync服务启动脚本

#!/bin/sh
if [ $# -ne ]
then
echo $"usage:$0{start|stop|restart}"
exit
fi
if [ "$1" = "start" ]
then
rsync --daemon
if [ `netstat -lntup|grep rsync|wc -l` -ge ]
then
echo "rsyncd is started."
exit
fi
elif [ "$1" = "stop" ]
then
pkill rsync
if [ `netstat -lntup|grep rsync|wc -l` -eq ]
then
echo "rsyncd is stopped."
exit
fi
elif [ "$1" = "restart" ]
then
pkill rsync
sleep
rsync --daemon
else
echo $"usage:$0{start|stop|restart}"
exit
fi

参考学习:https://blog.51cto.com/oldboy/1855639

shell 学习笔记7-shell-函数的更多相关文章

  1. Shell学习笔记之shell脚本和python脚本实现批量ping IP测试

    0x00 将IP列表放到txt文件内 先建一个存放ip列表的txt文件: [root@yysslopenvpn01 ~]# cat hostip.txt 192.168.130.1 192.168.1 ...

  2. linux shell学习笔记二---自定义函数(定义、返回值、变量作用域)介绍

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用.下面说说它的定义方法,以及调用需要注意那些事项. 一.定义shell函数(define function) 语法: [ f ...

  3. 鸟书shell 学习笔记(一) shell专注于概念和命令

    变量   variableName=value 等号左右不能有空格 变量内容有空格须要用"或者'括起来,可是 v="hello $name" $保持原有功能,单引號则不行 ...

  4. shell学习笔记2: shell中的四则运算符

    shell中的四则运算符 n1,n2 :常量数字 char:运算符号 加,减,乘,除,取余(+,-,*,/,%) $a,$b:变量a,变量b 方法1 数字与符号之间需要有空格 不支持小数 expr n ...

  5. 鸟书shell 学习笔记(二) shell中正則表達式相关

    通配符与正則表達式的差别 通配符是bash原生支持的语法,正則表達式是处理字符串的一种表示方式, 正則表達式须要支持的工具支持才干够 语系设置 : export LANG=C grep alias 设 ...

  6. shell学习笔记1: shell 中的变量与常见符号使用方法

    变量 声明即用 a=2 b="123" 调用 ${varName}或者 $varName echo $b echo ${a} 常见变量 $?:判断上一个语句是否成功 $0:执行脚本 ...

  7. shell学习笔记汇总

    1.shell脚本中函数使用 函数定义在前,调用在后,顺序反了就没有效果了.函数调用为:函数名 参数列表 函数内部通过以下变量访问函数的参数:shell脚本函数中: $0: 这个脚本的名字 $n: 这 ...

  8. SHELL学习笔记三

    SHELL学习笔记一 SHELL学习笔记二 SHELL学习笔记三 for 命令 读取列表中的复杂值 从变量读取列表 从命令读取值 更改字段分隔符 用通配符读取目录 which 使用多个测试命令 unt ...

  9. shell学习笔记

    shell学习笔记 .查看/etc/shells,看看有几个可用的Shell . 曾经用过的命令存在.bash_history中,但是~/.bash_history记录的是前一次登录前记录的所有指令, ...

  10. [转帖][Bash Shell] Shell学习笔记

    [Bash Shell] Shell学习笔记 http://www.cnblogs.com/maybe2030/p/5022595.html  阅读目录 编译型语言 解释型语言 5.1 作为可执行程序 ...

随机推荐

  1. python : 设计模式之外观模式(Facade Pattern)

    #为啥要用外观模式举例说明 这个例子很形象,直接从人家博客上贴过来的,参考链接在下面 不知道大家有没有比较过自己泡茶和去茶馆喝茶的区别,如果是自己泡茶需要自行准备茶叶.茶具和开水,如图1(A)所示,而 ...

  2. Mac OS docker挂载文件夹

    sudo docker run -p 3306:3306 --name mysql -v /var/run/docker.sock:/var/run/docker.sock -v ~/mysql/co ...

  3. ISO/IEC 9899:2011 条款6.7.4——函数说明符

    6.7.4 函数说明符 语法 1.function-specifier: inline _Noreturn 约束 2.函数说明符应该只能被用在对一个函数标识符的声明中. 3.对一个含有外部连接函数的内 ...

  4. OMPL RRTConnet 生成路径和可视化

    默认规划路径算法和RRTConnet路径规划算法生成路径 1.  源代码 #include <ompl/base/SpaceInformation.h> #include <ompl ...

  5. C#关于时间(获取特定格式的时间及多种方式获取当前时间戳)以及10位和13位时间戳转为特定格式

    C#关于时间(获取特定格式的时间及多种方式获取当前时间戳)以及10位和13位时间戳转为特定格式 置顶 2018年03月06日 19:16:51 黎筱曦 阅读数:19098 标签: C#时间 更多 个人 ...

  6. SERVER_ADDR

    $_SERVER["SERVER_ADDR"]  当前运行脚本的服务器的ip地址

  7. Sublime Text 3能用支持的插件推荐

    从二月份用测试版本build 3012开始用sublime text 3,虽然很多插件在sublime text 3不工作了,因为sublime text 3修复了2的一些bug.提升了性能并集成了不 ...

  8. 【Leetcode_easy】994. Rotting Oranges

    problem 994. Rotting Oranges 参考 1. Leetcode_easy_994. Rotting Oranges; 完

  9. hadoop(四)MapReduce

    如果将 Hadoop 比做一头大象,那么 MapReduce 就是那头大象的电脑.MapReduce 是 Hadoop 核心编程模型.在 Hadoop 中,数据处理核心就是 MapReduce 程序设 ...

  10. 【NER】对命名实体识别(槽位填充)的一些认识

    命名实体识别 1. 问题定义 广义的命名实体识别是指识别出待处理文本中三大类(实体类.时间类和数字类).七小类(人名.机构名.地名.日期.货币和百分比)命名实体.但实际应用中不只是识别上述所说的实体类 ...