需要注意的是:在windows下写的Shell脚本在Linux中运行时,需要首先运行dos2unix

1、判断文件或字符串的后缀名

       [root@storm2.ssh]# expr "zookeeper.out" : ".*\.pub"

       0

       [root@storm2.ssh]# expr "id_rsa.pub" : ".*\.pub"

       10  

       其中10是匹配后的字符数

2、判断数字是否为整数

       #!/bin/sh

       #Author:Johnny.zhao

       #fileName:chkInt.sh

       #descrption:checkinput is int or chars

 

       whiletrue

       do

            read -p "Please input:" a

            expr $a + 0 >/dev/null 2>&1

            [ $? -eq 0 ] && echo int||echochars

       done

       运行情况如下:[root@storm2shell]# sh chkInt.sh

                            Pleaseinput:abc

                            chars

                            Pleaseinput:123

                            int

                            Pleaseinput:

3、计算字符串长度

       [root@storm2shell]# expr length "abc"

       3

       [root@storm2shell]# expr length ./chkInt.sh

       11

4、判断是否为数字

       原理:就是将数字和减号都去掉如果不为空就不是数字

       方法1:

              expr$1 + 0 >/dev/null 2>&1

              [$? -eq 0 ] && echo "int"

       方法2:

              a=`echo$a|sed 's/[0-9]//g' | sed 's/-//g'`

              ["$a" = "" ]&&echo "int"||echo "Notint"

5、判断文件是否存在

       test-f file&&echo 1|| echo 0

       文件存在就显示1,否则显示0

       第二种方法:

              [-f file ]&& cat file

6、判断MySQL进程是否启动,否则就启动

    这种比较简单,实际上要考虑的还要复杂些,可以百度下,基本原理如下:

       portNum=`netstat-lnt|grep 3306|wc -l`

       mysqlProcess=`ps-ef|grep mysqld|grep -v grep|wc -l`

       #canuse portNum if 1:running,如果是1表示启动了一个3306端口

       #canuse process if 1:running,如果是1,表示启动了一个mysqld进程

       #if[ portNum -eq 1 ];then

       if[ mysqlProcess -eq 1 ];then

            echo "mysql is running"

       else

            /data/3306/mysql start

       fi

7、判断Apache或nginx服务是否启动

       可以使用上面判断MySQL服务的方法,另外,也可以使用如下的方法:

       方法一:

              #!/bin/sh

              httpPortNum=`nmap192.168.25.43 -p 80|grep open|wc -l`

              if[ $httpPortNum -eq 1 ];then

                     echo"httpd is running!!"

              else

                     echo"httpd is not running!!"

                     /application/apache/bin/apachectlstart

              fi 

       方法二(模拟远程获取资源):

              #!/bin/sh

              wget-T 10 -q --spider http://192.168.25.43 >&/dev/null

              #也可以使用curl

              #curl-s http://192.168.25.43 >&/dev/null

              if[ $? -eq 0 ];then

                     echo"httpd is running!!"

              fi

       方法三:(通过httphead的状态码判断)

              #!/bin/sh

              httpCode=`curl-I -s 192.168.25.43|head -1|cut -d " " -f2`

              if[ "$httpCode" = "200" ]

              then

                     echo"apache is running!!"

              fi

              显示的好看一点:

              #!/bin/sh

              [ -f /etc/init.d/functions ]&& ./etc/init.d/functions||exit 1

              httpCode=`curl-I -s 192.168.25.43|head -1|cut -d " " -f2`

              if[ "$httpCode" = "200" ];then

                     action"nginx is running!!" /bin/true

              else

                     action"nginx is not running !!" /bin/false

                     sleep1

                     /application/nginx/sbin/nginx&& \

                     action"nginx is running !!" /bin/true

              fi

8、使用nc判断远程端口是否开启,还可以使用nmap/telnet

       nc-w 5 www.baidu.com 80 &&echo "ok"||echo "no"

9、vi界面中的字体颜色:

       echo-e "\033[30m 黑色字 \033[0m"

       echo-e "\033[31m 红色字 \033[0m"

       echo-e "\033[32m 绿色字 \033[0m"

       echo-e "\033[33m 黄色字 \033[0m"

       echo-e "\033[34m 蓝色字 \033[0m"

       echo-e "\033[35m 紫色字 \033[0m"

       echo-e "\033[36m 天蓝字 \033[0m"

       echo-e "\033[37m 白色字 \033[0m"

       如果需要在sh中使用,可以使用如下方式

       #!/bin/sh

       Red_Color='\E[1;31m'

       Green_Color='\E[1;32m'

       Yellow_Color='\E[1;33m'

       Blue_Color='\E[1;34m'

       Pink_Color='\E[1;35m'

       End_Color='\E[0m'

   echo -e "${Red_Color}===redcolor===${End_Color}"

   echo -e "${Green_Color}===greencolor===${End_Color}"

10、case常用写法

       #!/bin/sh

       Red_Color='\E[1;31m'

       Green_Color='\E[1;32m'

       Yellow_Color='\E[1;33m'

       Blue_Color='\E[1;34m'

       Pink_Color='\E[1;35m'

       End_Color='\E[0m'

       case"$1" in

         "red")

            echo-e "${Red_Color}===red color===${End_Color}"

            ;;

         "green"|"GREEN")

            echo-e "${Green_Color}===green color===${End_Color}"

            ;;

         *)

            ;;

       esac

11、使用while读取文件内容

       #!/bin/sh

       whileread line

       do

              echo$line

       done< /etc/profile

       其中line指每行的内容,done< 需要附加读取文件的路径      

12、for循环

       #!/bin/sh

       #数字使用空格进行分隔,可以使用的方式有:

       #1、    for i in 1 2 3 ..

       #2、        for i in {1..10}

       fori in `seq -s " " 10`      

       do

              echo$i

       done 

13、Shell产生随机数的几种方法:

       echo"$RANDOM"           

       echo"$(date +%N%s)"

       opensslrand -base64 8        #base64编码8为随机数,

       cat/proc/sys/kernel/random/uuid #获取uuid

       方法五:

       yuminstall expect -y

       mkpasswd-l 8

      

       对于上面随机数的结果长短不一,如果需要取8位,可以使用管道,然后添加md5,然后截取

       eg:echo "$RANDOM|md5sum|cut -c 15-22"|bash

14、函数的用法

       函数定义:

       functionmethodName(){

              method..

       }   其中function可以省略

       定义函数要在/etc/init.d下,因为系统函数也在这里

       eg

       vimy_functions

       #!/bin/sh

       functionxiaoming(){

              echo"I'm $1"

       }

 

       赋予执行权限

       chomod+x ./my_functions

       调用

       vitest.sh

       #!/bin/sh

       #加载自定义函数

       [-x /etc/init.d/my_functions ] && . /etc/init.d/my_functions ||{

              echo"加载函数my_functions 有误"

       } 

       xiaoming"Jack"

15、生产环境批量检测web URL

       用途:一般用来重复Apache或nginx后检查web是否启动成功

   #!/bin/sh

   #Email:..

   #Functions:..

   #Version:..

   #Create by 2015.05.10

   urlPath="/usr/local/shell/url.txt"

   for url in $(cat ${urlPath})

   do

          #-o输出内容到/dev/null;-s静默方式;-w 定义显示输出格式;'%{http_code}'在最后被检索的http

          #页面中找到的数字代码

          httpCode=`curl -o /dev/null -s -w"%{http_code}" "${url}"`

          if [ ${httpCode} -ne 200 ]

          then

                 echo -e "the url has error\nthe chkUrl is ${url}"|mail -s "url_error"test@test1.com,test@test2.com

          fi

    done

16、Linux一键优化

       可以优化的内容:

              1)安装系统时精简安装包(最小化安装)

              2)配置国内高速yum源

              3)禁用开机不需要启动的服务

              4)优化系统内核参数/etc/sysctl.conf

              5)增加系统文件描述符、堆栈等配置

              6)禁止root远程登录,修改SSH端口为特殊端口,禁用DNS、空密码

              7)有外网IP的机器要开启配置防火墙,仅对外开启需要提供服务的端口,配置或关闭SELINUX

              8)清除无用的默认系统帐户或组(非必须)(添加运维成员的用户)

              9)锁定敏感文件,如/etc/passwd(非必须)

              10)配置服务器和互联网时间同步

              11)配置sudo对普通用户权限精细控制

       一键优化脚本可以优化的内容(2、3、4、5、6、7、10)

       脚本  部分优化函数

       #!/bin/sh

       #setenv

       exportPATH=$PATH:/bin:/sbin:/usr/sbin

       exportLANG="zh_CN.GB18030"

       #Requireroot to run this script

       if[[ "$(whoami)"!="root" ]];then

              echo"Please run this script as root.">&2

              exit1

       fi

       #definecmd var

       SERVICE="whichservice"

       CHKCONFIG="whichchkconfig"

       #sourcefunction library

       ./etc/init.d/functions

      

       #configYum CentOS-Base.repo

       ConfigYum(){

              echo"Config Yum CentOS-Base.repo"

              cd/etc/yum.repos.d/

              \cpCentOS-Base.repo CentOS-Base.repo.seven.$(date +%F)

              ping-c 1 baidu.com>/dev/null

              [$? -ne 0 ]&& echo $"Networking not configured-exiting"&&exit 1

              wget--quiet -o /dev/null http://mirrors.sohu.com/help/CentOS-Base-sohu.repo

              \cpCentOS-Base-sohu.repo CentOS-Base.repo

       }

      

       #InstallChinese Package

       #yum-y install fonts-chinese fonts-ISO8859-2>/dev/null 2>&1

       #Installinit Package

       installTool(){

              echo"sysstat ntp net-snmp lrzsz rsync"

              yum-y install sysstat ntp net-snmp lrzsz rsync >/dev/null 2>&1

       }

       #CharsetGB18030

       initI18n(){

              echo'#set LANG="zh_cn.gb18030"'

              \cp/etc/sysconfig/i18n /etc/sysconfig/i18n..$(date +%F)

              sed-i 's#LANG="en_US.UTF-8"#LANG="zh_CN.GB18030"#' /etc/sysconfig/i18n

              source/etc/sysconfig/i18n

              grepLANG /etc/sysconfig/i18n

              sleep1

       }  

       #CloseSelinux and Iptables

       #设置永久生效和临时生效,因为永久生效需要重启,在添加临时生效就不需要重启了

       initFireWall(){

              echo"#Close SeLinux and Iptables"

              cp/etc/selinux/config /etc/selinux/config.`date +"%Y-%m-%d_%H-M-%S"`

              /etc/init.d/iptablesstop

              sed-i 's/SELINUX=enable/SELINUX=disable' /etc/selinux/config

              setenforce0

              /etc/init.d/iptablesstatus

              grepSELINUX=disabled /etc/selinux/config

              echo"Close selinux -> OK and iptables -> OK"

              sleep1

       }

       #initauto Startup Service

       initService(){

              echo"Close Nouseful Service"

              exportLANG="en_US.UTF-8"

              foroldboy in `chkconfig --list|grep 3:on|awk '{print $1}'`;do chkconfig --level 3$oldboy off;done

              foroldboy in crond network syslog ssoldboy;do chkconfig --level 3 $oldboy on;done

              exportLANG="zh_CN.GB18030"

              echo"关闭不需要的服务--> OK"

              sleep1

       }

       initSsh(){

              echo"#-----sshConfig 修改ssh默认登陆端口,禁止root登陆-----"

              \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/sshdreload && action $"修改ssh默认端口,禁止root登陆:" /bin/true||action \

              $"修改ssh默认端口,禁止root登陆:"/bin/false

             

       }

       addSysUser(){

              echo"#-----添加系统用户------"

              datetmp=`date+"%Y-%m-%d_%H-%M-%S"`

              \cp/etc/sudoers /etc/sudoers.${datetmp}

              saUserArr=(oldboyoldboy1 oldboy2)

              groupadd-g 888 sa

              for((i=0;i<${saUserArr[@]};i++))

              do

                     #adduser

                     useradd-g sa -u 88${i} ${saUserArr[$i]}

                     #设置密码

                     echo"${saUserArr[$i]}123"|passwd ${saUserArr[$i]} --stdin

                     #设置sudo权限

                     #[$(grep "${saUserArr[$i]} ALL=(ALL) NOPASSWD: ALL" /etc/sudoers|wc -l)-le 0 ]&&echo \

                     "${saUserArr[$i]}ALL=(ALL) NOPASSWD:ALL" >>/etc/sudoers

                     [`grep "\%sa"|grep -v grep |wc -l` -ne 1 ] &&\

                     echo"%sa ALL=(ALL) NOPASSWD:ALL">>/etc/sudoers

              done

              /usr/sbin/visudo-c

              [$? -ne 0 ]&& /bin/cp /etc/sudoers.${datetmp} /etc/sudoers &&echo $"Sudoers not configured -exiting"\

              &&exit 1

              action$"用户添加成功 --> OK" /bin/true

       }

       #设置系统同步时间----

       syncSystemTime(){

              #同步时间

              if[ `grep pool.ntp.org /var/spool/cron/root|grep -v grep|wc -l` -lt 1 ];then

                     echo"*/5 * * * * /usr/sbin/ntpdate cn.pool.ntp.org >/dev/null2>&1" >> /var/spool/cron/root

              fi

       }

       #调整打开文件数

       openFiles(){

              echo"------------调整最大打开系统文件格式为65535个---------------"

              \cp/etc/security/limits.conf /etc/security/limits.conf.`date +%Y-%m-%d_%H-%M-%S`

              sed-i '/# End of file/i\*\t\t-\tnofile\t\t65535' /etc/security/limits.conf

              ulimit-HSn 65535

              echo"调整最大打开系统文件个数成功!(修改后重新登陆生效)"

              sleep1

       }

       #优化系统内核---------------------------

       optimizationKernal(){

              echo"优化系统内核----->"

              \cp/etc/sysctl.conf /etc/sysctl.conf.`date +"%Y-%m-%d_%H-%M-%S"`

              cat>>/etc/sysctl.conf<<EOF

              net.ipv4.tcp_timestamps= 0

              net.ipv4.tcp_synack_retries= 2

              net.ipv4.tcp_syn_retries= 2

              net.ipv4.tcp_mem= 94500000 915000000 927000000

              net.ipv4.tcp_max_orphans= 3276800

              net.core.wemem_default= 8388608

              net.core.rmem_default= 8388608

              net.core.rmem.max= 16777216

              net.core.wmem_max= 16777216

              net.ipv4.tcp_rmem=409687380 16777216

              net.ipv4.tcp_wmem=409687380 16777216

              net.core.netdev_max_backlog= 32768

              net.core.somaxcom= 32768

              net.ipv4.tcp_syncookies=1

              net.ipv4.tcp_tw_reuse= 1

              net.ipv4.tcp_tw_recycle= 1

              net.ipv4.tcp_fin_timeout= 1

              net.ipv4.tcp_keepalive_time=600

              net.ipv4.tcp_max_syn_backlog= 65536

              net.ipv4.ip_local_port_range= 1024 65535

       EOF

       /sbin/sysctl-p && action $"内核优化:" /bin/true||action $"内核优化:"/bin/false

       }

      

       #----------------------------

       initSafe(){

              echo"----------禁止ctrl+alt+del三个键重启系统-----------------"

              cp/etc/inittab /etc/inittab.`date +"%Y-%m-%d_%H-%M-%S"`

              sed-i "s/ca::ctrlaltdel:\/sbin\/shutdown -t3 -rnow/#ca::ctrlaltdel:\/sbin\/shutdown -t3 -r now/" \

              /etc/inittab

              /sbin/initq

              [$? -eq 0 ]&&action $"禁止 Ctrl+alt+delete三个键重启系统:"/bin/true|| \

              action$"禁止 Ctrl+alt+delete三个键重启系统:" /bin/false

       }

17、数组

       定义:arr=(1 23)

       数组长度:echo${#arr[@]}

       也可以使用:echo${#arr[*]}

       获取数组内容:echo${arr[*]}或者echo ${arr[@]}

       元素修改arr[0]="china"

       元素删除 unsetarr[0]

       数组删除 unsetarr

18、使用系统变量定义数组并且遍历

       第二种定义数组的方式:arr=($(ls))

       forfile in `ls ./`

       do

              echo$file

       done

       arr1=($(ls))

       forfile in ${arr1[*]}

       do

              echo$file

       done

      

       for((i=0;i<`echo ${#arr1[*]}`;i++))

       do

              echo${arr1[$i]}

       done

19、利用数组检查多个URL地址

    说明:一般来说超时应该在10s左右比较合理

       #!/bin/sh

       ./etc/init.d/functions

      

       #定义数组

       url_list=(

              http://baidu.com

              http://taobao.com

              http://192.168.10.2

       )

       functionwait(){

              echo-n '3秒钟后执行该操作'

              for((i=0;i<3;i++))

              do

                     echo-n ".";sleep 1

              done

       }

       wait

       echo"检查URL地址..."

       #检查URL地址

       functioncheck_url(){

              for((i=0;i<${#url_list[*]};i++))

              do

                     #urlArr=($(curl-o >/dev/null -s -w "%{http_code}" "$url_list[$i]"))

                     urlArr=($(curl-I --connect-timeout 2 -s ${url_list[$i]}|head -1|tr "\r""\n"))

                     if[ "${urlArr[1]}" = "200" -a "${urlArr[2]}" ="OK" ]

                     then

                            action"${url_list[$i]} 连接成功:" /bin/true

                     else

                            action"${url_list[$i]} 连接成功:" /bin/false

                     fi

              done

       }

       check_url

20、使用bash命令参数调试

       sh[-nvx] abc.sh

       -n:不会执行该脚本,仅仅是查询脚本语法是否有问题,并进行提示

       -v:在执行脚本时,先将内容输出到屏幕上,然后在执行,如果有错误,会进行错误提示

       -x:将执行的脚本内容及输出显示到屏幕上。这也是最常用的调试参数

      

       如果脚本较大,还可以使用set-x(开始) 和set +x(结束)进行部分脚本的调试

       eg:

              #!/bin/sh

              echo"..."

              set-x

              fori in `ls`

              do

                     echo$i

              done

              set+x

              ...

     

 
 
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐