Linux Shell脚本经典案例

编写Shell过程中注意事项:
开头加解释器:#!/bin/bash
语法缩进,使用四个空格;多加注释说明 。
命名建议规则:变量名大写、局部变量小写,函数名小写,名字体现出实际作用 。
默认变量是全局的,在函数中变量local指定为局部变量,避免污染其他作用域 。
有两个命令能帮助我调试脚本:set -e 遇到执行非0时退出脚本,set-x 打印执行过程 。
写脚本一定先测试再到生产上 。

Linux Shell脚本经典案例

文章插图
 
1、获取随机字符串或数字获取随机8位字符串:
方法1:
# echo $RANDOM |md5sum |cut -c 1-8
471b94f2
方法2:
# openssl rand -base64 4
vg3BEg==
方法3:
# cat /proc/sys/kernel/random/uuid |cut -c 1-8
ed9e032c
获取随机8位数字:
方法1:
# echo $RANDOM |cksum |cut -c 1-8
23648321
方法2:
# openssl rand -base64 4 |cksum |cut -c 1-8
38571131
方法3:
# date +%N |cut -c 1-8
69024815
cksum:打印CRC效验和统计字节
2、定义一个颜色输出字符串函数
方法1:
function echo_color() {
if [ $1 == "green" ]; then
echo -e "33[32;40m$233[0m"
elif [ $1 == "red" ]; then
echo -e "33[31;40m$233[0m"
fi
}
方法2:
function echo_color() {
case $1 in
green)
echo -e "[32;40m$2[0m"
;;
red)
echo -e "[31;40m$2[0m"
;;
*)
echo "Example: echo_color red string"
esac
}
使用方法:echo_color green "test"
function关键字定义一个函数,可加或不加 。
3、批量创建用户
#!/bin/bash
DATE=$(date +%F_%T)
USER_FILE=user.txt
echo_color(){
if [ $1 == 'green' ]; then
echo -e "[32;40m$2[0m"
elif [ $1 == 'red' ]; then
echo -e "[31;40m$2[0m"
fi
}
# 如果用户文件存在并且大小大于0就备份
if [ -s $USER_FILE ]; then
mv $USER_FILE $USER_FILE-$DATE.bak
echo_color green "$USER_FILE exist, rename ${USER_FILE}-${DATE}.bak"
fi
echo -e "User Password" >> $USER_FILE
echo "-------------------">> $USER_FILE
for USER in user{1..10}; do
if ! id $USER &>/dev/null; then
PASS=$(echo $RANDOM |md5sum |cut -c 1-8)
useradd $USER
echo $PASS |passwd --stdin $USER &> /dev/dell
echo -e "$USER $PASS" >> $USER_FILE
echo "$USER User create successful."
else
echo_color red "$USER User already exists!"
fi
done
4、检查软件包是否安装
#!/bin/bash
if rpm -q sysstat &>/dev/null; then
echo "sysstat is already installed."
else
echo "sysstat is not installed!"
fi
5、检查服务状态
#!/bin/bash
PORT_C=$(ss -ant |grep -c 6443)
PS_C=$(ps -ef |grep kube-apiserver |grep -vc grep)
if [ $PORT_C -eq 0 -o $PS_C -eq 0 ]; then
echo "kube-apiserver service dowmped"
else
echo "kube-apiserver service running!"
fi
6、检查主机存活状态方法1:将错误IP放到数组里面判断是否ping失败三次
#!/bin/bash
for IP in $IP_LIST; do
NUM=1
while [ $NUM -le 3 ]; do
if ping -c 1 $IP &> /dev/null; then
echo "$IP Ping is successful."
break
else
FAIL_COUNT[$NUM]=$IP
let NUM++
fi
done
if [ ${#FAIL_COUNT[*]} -eq 3 ]; then
echo "${FAIL_COUNT[1]} Ping is failure!"
unset FAIL_COUNT[*]
fi
done
方法2:将错误次数放到FAIL_COUNT变量里面判断是否ping失败三次
#!/bin/bash
for IP in $IP_LIST; do
FAIL_COUNT=0
for (( i=1;i<=3;i++)); do
if ping -c 1 $IP &>/dev/null; then
echo "$IP Ping is successful."
break
else
let FAIL_COUNT++
fi
done
if [ $FAIL_COUNT -eq 3 ]; then
echo "$IP Ping is failure!"
fi
done
方法3:利用for循环将ping通就跳出循环继续,如果不跳出就会走到打印ping失败
#!/bin/bash
ping_success_status() {
if ping -c 1 $IP &>/dev/null; then
echo "$IP Ping is successful."
continue
fi
}
for IP in $IP_LIST; do
ping_success_status


推荐阅读