1、获取随机字符串或数字
方法一:
[root@centos ~]# vim random.sh
#!/bin/bash
function print_random() {
for i in {
1..10};
do
echo -e "$i \t $RANDOM"
done
}
print_random
[root@centos ~]# sh random.sh
方法二:date随机数法
[root@centos ~]# vim date.sh
#!/bin/bash
a=`date +%s%N`
echo $a
[root@centos ~]# sh date.sh
方法三:通过内部系统变量
[root@centos ~]# echo $RANDOM
5173
[root@centos ~]# echo $RANDOM
9792
2、定义一个颜色输出字符串函数
[root@centos ~]# vim color.sh
#!/bin/bash
color(){
if [ $1 == "red" ]
then
echo -e "\033[31m$2\033[0m"
elif [ $1 == "green" ]
then
echo -e "\033[32m$2\033[0m"
elif [ $1 == "blue" ]
then
echo -e "\033[36m$2\033[0m"
fi
}
color green "绿色"
color red "红色"
[root@centos ~]# sh color.sh
绿色
红色
关于shell脚本字体颜色拓展


3、批量创建用户
#!/bin/bash
read -p "please input passwd:" PASSWD
for UNAME in `cat file4`
do
id $UNAME &> /dev/null
if [ $? -eq 0 ]
then
echo "the $UNAME already exist"
else
useradd $UNAME &> /dev/null
echo $PASSWD | passwd --stdin $UNAME &> /dev/null
if [ $? -eq 0 ]
then
echo "$UNAME create sucessful"
else
echo "$UNAME create failed"
fi
fi
done
4、检查软件包是否安装
rpm -ivh your-package # 直接安装
rpmrpm --force -ivh your-package``.rpm # 忽略报错,强制安
[root@localhost ~]# rpm -ql tree # 查询
[root@localhost ~]# rpm -e tree # 卸载
[root@localhost ~]# rpm -ql tree # 查询
#!/bin/bash
read -p

本文介绍了多个Shell脚本基础练习,包括如何批量创建用户、检查软件安装、检测主机存活状态、监控系统资源、处理DOS攻击等,深入探讨了shell脚本中的变量定义、字符串操作、循环与条件判断等核心概念。
&spm=1001.2101.3001.5002&articleId=107067687&d=1&t=3&u=c9bf93d664fc4afd8b248a6973fd5c02)

被折叠的 条评论
为什么被折叠?



