shell腳本經常使用技巧shell
1.獲取隨機字符串或數字bash
~]#echo $RANDOM | md5sum | cut -c 1-6
~]#openssl rand -base64 4 | cut -c 1-6
~]#uuidgen | cut -c 1-6
2.獲取隨機數ui
~]#echo $RANDOM | cksum | cut -c 1-6
~]#openssl rand -base64 4 | chsum | cut -c 1-6
~]#date +%N | cut -c 1-6
3.自定義顏色輸出字符串spa
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.批量建立用戶3d
#!/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.檢查軟件包是否安裝code
#!/bin/bash if rpm -q sysstat &>/dev/null; then echo "sysstat is already installed!" else echo "sysstat is not installed!" fi
6.檢查服務狀態blog
#!/bin/bash PORT_C=$(ss -anu | grep -c 123) PS_C=$(ps -ef | grep -ntpd | grep -vc grep) if [ $PORT_C -eq 0 -o $PS_C -eq 0 ];then echo "content" | mail -s "summary" dst@example.com fi
.md5