shell脚本常用技巧

时间:2022-05-29 21:57:09

shell脚本常用技巧

1.获取随机字符串或数字

~]#echo $RANDOM | md5sum | cut -c 1-6

shell脚本常用技巧

~]#openssl rand -base64 4 | cut -c 1-6

shell脚本常用技巧

~]#uuidgen | cut -c 1-6

shell脚本常用技巧

2.获取随机数

~]#echo $RANDOM | cksum | cut -c 1-6

shell脚本常用技巧

~]#openssl rand -base64 4 | chsum | cut -c 1-6

shell脚本常用技巧

~]#date +%N | cut -c 1-6

shell脚本常用技巧

3.自定义颜色输出字符串

function echo_color () {
if [ $1 == "green" ]; then
echo -e "\033[32;40m$2\033[0m"
elif [ $1 == "red" ]; then
echo -e "\033[31;40m$2\033[0m"
fi
}
function echo_color () {
case $1 in
green)
echo -e "\033[032;40m$2\033[0m"
;;
red)
echo -e "\033[032;40m$2\033[0m"
;;
*)
echo "Example: echo_color green string"
esac
}

4.批量创建用户

#!/bin/bash
DATE=$(date +%F_%T)
USER_FILE=user.txt echo_color () {
if [ $1 == "green" ];then
echo -e "\033[032;40m$2\033[0m"
elif [ $1 == "red" ];then
echo -e "\033[031;40m$2\033[0m"
fi
} 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 "Users\tPassword" >> $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/null
echo -e $USER\t$PASS >>$USER_FILE
echo "$USER User create successful."
else
echo_color red "$USER User already exists."
fi
done

5.检查软件包是否安装

#!/bin/bash
if rpm -q sysstat &>/dev/null; then
echo "sysstat is already installed!"
else
echo "sysstat is not installed!"
fi

6.检查服务状态

#!/bin/bash
PORT_C=$(ss -anu | grep -c )
PS_C=$(ps -ef | grep -ntpd | grep -vc grep)
if [ $PORT_C -eq -o $PS_C -eq ];then
echo "content" | mail -s "summary" dst@example.com
fi

.