Shell 是用户与 Linux 操作系统之间沟通的桥梁。用户可以输入命令执行,又可以利用
Shell 脚本编程去运行。随着 Linux 企业应用越来越多,维护 Linux 日常工作频繁,所以如
果单靠手工去敲打命令是非常困难的,学会熟练使用SHELL编程是每个Linux SA必备功课。
Linux Shell种类非常多,常见的有:Bourne Shell(/usr/bin/sh或/bin/sh)、Bourne Again Shell
(/bin/bash)、C Shell(/usr/bin/csh)、K Shell(/usr/bin/ksh)、Shell for Root(/sbin/sh)等。
不同的 Shell 语言的语法有所不同,所以不能交换使用。
最常用的 shell 是 Bash,也就是 Bourne Again Shell,由于易用和免费,Bash 在日常工作
中被广泛使用,也是大多数 Linux 系统默认的 Shell。

1、创建第一个helloworld.sh

# vi helloworld.sh

//输入内容
#!/bin/bash
#This is my First shell
echo “Hello World !” 

解释信息:
#!/bin/bash //表示定义该脚本是一个 shell 脚本(固定格式)。
#This is my First shell //这里的#号属于注解,没有任何的意义,SHELL 不会解析它。
echo “Hello World !” //shell 脚本主命令,我们执行这个脚本看到: Hello World ! 信息。

2、变量

#!/bin/bash
#This is variable
A=123
echo “Printf variables equal is $A”

输出 Printf variables equal is123

3、流程控制

eg1:
#!/bin/sh
NUM=100
if (( $NUM > 4 )) ;then
    echo "this num is $NUM greater 4 !"
else
    echo "this num is $NUM littel 4 !"
fi

输出this num is 100 greater 4 !

eg2:
#!/bin/sh
#judge dir exist
if [ ! -d /data/20210204 ];then
    mkdir -p /data/20210204
else
    echo “This DIR is exist,Please exit..fi

逻辑运算符解析:
-f 判断文件是否存在 eg: if [ -f filename ]
-d 判断目录是否存在 eg: if [ -d dir ]
-eq 等于 应用于:整型比较
-ne 不等于 应用于:整型比较
-lt 小于 应用于:整型比较
-gt 大于 应用于:整型比较
-le 小于或等于 应用于:整型比较
-ge 大于或等于 应用于:整型比较
-a 双方都成立(and) 逻辑表达式 –a 逻辑表达式
-o 单方成立(or) 逻辑表达式 –o 逻辑表达式
-z 空字符串

eg3:多个条件测试判断,两个中括号[[]]用于逻辑运算比较大小
#!/bin/sh
scores=80;
if [[ $scores -gt 85 ]]; then
    echo "very good!";
elif [[ $scores -gt 75 ]]; then
    echo "good!";
elif [[ $scores -gt 60 ]]; then
    echo "pass!";
else
    echo "no pass!";
fi;

3、循环语句 for while

eg1:
#!/bin/sh
for i in `seq 15`
do
    echo “NUM is $idone

eg2:找到相关log,然后批量打包
#!/bin/sh
for i in `find /var/log -name “*.log”`
do
    tar –czf 2014log.tgz $i
done

eg3: while判断数字(输出1到9)
#!/bin/sh
i=1;
while [[ $i -lt 10 ]];do
    echo $i;
    ((i++));
done;

4、Shell编程函数(shell允许降一组命令集或语句形成一个可用块,这些块成为shell函数)

function shellname(){ 
    command
}

5、Until循环语句

#!/bin/sh
a=10;
until [[ $a -lt 0 ]];do
echo $a;
((a--));
done;

6、case选择语句

#!/bin/sh
case $1 in
monitor_log)
monitor_log
;;
archive_log)
archive_log
;;
*
)
echo "Usage:{$0 monitor_log | archive_log |help }"
;;
esac

7、select选择语句

#!/bin/sh
PS3="What you like most of the open source system?"
select i in CentOS RedHat Ubuntu
do
echo "Your Select System: "$i
done

8、shell数组编程

#!/bin/sh
#Auto Make KVM Virtualization
#Auto config bond scripts
eth_bond()
{
NETWORK=(
    HWADDR=`ifconfig eth0 |egrep "HWaddr|Bcast" |tr "\n" " "|awk '{print $5,$7,$NF}'|sed -e
                        's/addr://g' -e 's/Mask://g'|awk '{print $1}'`
    IPADDR=`ifconfig eth0 |egrep "HWaddr|Bcast" |tr "\n" " "|awk '{print $5,$7,$NF}'|sed -e
                        's/addr://g' -e 's/Mask://g'|awk '{print $2}'`
    NETMASK=`ifconfig eth0 |egrep "HWaddr|Bcast" |tr "\n" " "|awk '{print $5,$7,$NF}'|sed -e
                        's/addr://g' -e 's/Mask://g'|awk '{print $3}'`
    GATEWAY=`route -n|grep "UG"|awk '{print $2}'`
)
cat >ifcfg-bond0<<EOF
DEVICE=bond0
BOOTPROTO=static
${NETWORK[1]}
${NETWORK[2]}
${NETWORK[3]}
ONBOOT=yes
TYPE=Ethernet
NM_CONTROLLED=no
EOF

9、脚本案例

#!/bin/bash
#This is First shell for auto cp Files
#定义文件和目录变量
FILES=/root/test.txt
DIR=/tmp
cp $FILES $DIR
cd $DIR ; mkdir –p abc
rm -rf $FILES
echo “The Shell Scripts exec successfully !

10、自动备份MySQL数据库脚本

#!/bin/sh
#auto backup mysql
#Define PATH 定义变量
BAKDIR=/data/backup/mysql/`date +%Y-%m-%d`
MYSQLDB=webapp
MYSQLPW=backup
MYSQLUSR=backup
#must use root user run scripts 必须使用 root 用户运行,$UID 为系统变量
if [ $UID -ne 0 ]; then
    echo This script must use the root user ! ! !
    sleep 2
    exit 0
fi
#Define DIR and mkdir DIR 判断目录是否存在,不存在则新建
if [ ! -d $BAKDIR ]; then
    mkdir -p $BAKDIR
else
    echo This is $BAKDIR exists....
fi
#Use mysqldump backup mysql 使用 mysqldump 备份数据库
/usr/bin/mysqldump -u$MYSQLUSR -p$MYSQLPW -d
$MYSQLDB >$BAKDIR/webapp_db.sql
echo "The mysql backup successfully "

11、自动拒绝恶意IP脚本

#!/bin/sh
#auto drop ssh failed IP address
#定义变量
SEC_FILE=/var/log/secure
#如下为截取 secure 文件恶意 ip 远程登录 22 端口,大于等于 4 次就写入防火墙,禁止
以后再登录服务器的 22 端口
IP_ADDR=`tail -n 1000 /var/log/secure |grep "Failed password"| egrep
-o "([0-9]{1,3}\.){3}[0-9]{1,3}" | sort -nr | uniq -c |awk ' $1>=4 {print $2}'`
IPTABLE_CONF=/etc/sysconfig/iptables
echo
cat <<EOF
++++++++++++++welcome to use ssh login drop failed ip+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++
++++++++++++++++------------------------------------++++++++++++++++++
EOF
echo -n "请等待 5 秒后开始执行 "
for ((j=0;j<=4;j++)) ;do 
    echo -n "----------";
    sleep 1 ;
done
echo
for i in `echo $IP_ADDR`
do
#查看 iptables 配置文件是否含有提取的 IP 信息
cat $IPTABLE_CONF |grep $i >/dev/null
if [ $? -ne 0 ];then
    #判断 iptables 配置文件里面是否存在已拒绝的 ip,如何不存在就不再添加相应条目
    sed -i "/lo/a -A INPUT -s $i -m state --state NEW -m tcp -p tcp --dport 22 -j
    DROP" $IPTABLE_CONF
else
    #如何存在的话,就打印提示信息即可
    echo "This is $i is exist in iptables,please exit ......"
fi
done
#最后重启 iptables 生效
/etc/init.d/iptables restart

更多推荐

【CentOS7】Linux Shell脚本编程