9

循环脚本编写_10965183的技术博客_51CTO博客

 2 years ago
source link: https://blog.51cto.com/gavenlee/5763670
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

循环脚本编写

精选 原创

1、判断/var目录下所有文件的类型

#!/bin/bash
cd /var
File=`ls /var`
for i in *; do
file_type=`ls -ld $i |cut -b1`
case $file_type in
d)
echo "$i is 目录"
;;
l)
echo "$i is 链接文件"
;;
-)
echo "$i is 普通文件"
;;
b)
echo "$i is 设备文件"
;;
c)
echo "$i is 字符文件"
;;
esac

done
循环脚本编写_while read

2、添加10个用户user1-user10,密码为8位随机字符

#!/bin/bash
for i in {1..10}; do
id user$i &>/dev/null && echo "user$i is exit" || useradd user$i
User_passwd=`echo $RANDOM |md5sum | cut -c 1-8`
echo user$i:$User_passwd | chpasswd
echo "user$i $User_passwd">>a.txt
done
bug 如果账户存在会将密码重置,建议增加一次判断,替换成 id user$i &>/dev/null && { echo "user$i is exit";continue; },不能使用(),()开启子
循环脚本编写_for_02

3、计算100以内所有能被3整除的整数之和

循环脚本编写_while_03

4、在/testdir目录下创建10个html文件,文件名格式为数字N(从1到10)加随机8个字母,如: 1AbCdeFgH.html

循环脚本编写_while read_04
#!/bin/bash
mkdir testdir
cd testdir
for ((i=1;i<=10;i++));do
file_name=`openssl rand -base64 20 | sed -nr "s/[^a-Z]+//gp" | cut -c 1-8`
touch $i$file_name\.html
done

5、编写脚本,打印九九乘法表(用while)

循环脚本编写_while read_05
#!/bin/bash
i=1
while [ $i -lt 10 ];do
j=1
while [ $j -le $i ];do
echo -e "$i*$j=$[$i*$j]\t\c"
let j++
done
echo
let i++
done

6、编写脚本,利用变量RANDOM生成10个随机数字,输出这个10数字,并显示其中的最大值和最小值

循环脚本编写_continue_06
#!/bin/bash
i=1
while [ $i -le 10 ] ;do
ran=`openssl rand -base64 20 | cksum |cut -c 1-8`
echo $ran >>a.txt
if [ $i -eq 1 ];then
max=$ran
min=$ran
else
if [ $ran -ge $max ];then
max=$ran
elif [ $ran -le $min ];then
min=$ran
fi
fi
let i++
done
echo "max=$max min=$min"

7、后续六个字符串:efbaf275cd、4be9c40b8b、44b2395c46、f8c8873ce0、b902c16c8b、ad865d2f63是通过对随机数变量RANDOM随机执行命令: echo $RANDOM|md5sum|cut –c1-10后的结果,请破解这些字符串对应的RANDOM值

#!/bin/bash
cat a.txt | while read rand;do
{ while true;do
random=$RAMDOM
temp=`echo $random | md5sum | cut -c 1-10`
if [ "$ran" = "$temp" ];then
echo "$rand is $random md5"
break
fi
done }&
wait
done

12、编写猜数字游戏脚本提示比较大或小,相等则退出

循环脚本编写_continue_07
#!/bin/bash
let NUM=$RANDOM%10
while read -p "请猜数字:" Guess ;do
if [ $Guess -lt $NUM ];then
echo "猜小了"
elif [ $Guess -gt $NUM ];then
echo "猜大了"
else
echo "猜对了,是$NUM"
break
fi
done

13、用文件名做为参数,统计所有参数文件的总行数

循环脚本编写_for_08
#!/bin/bash
sum=0
while [ -n "$1" ];do
line=`wc -l $1 | grep -o "[0-9]\+"`
echo $1 $line
let sum+=line
shift
done
echo $sum
  • 收藏
  • 评论
  • 分享
  • 举报

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK