Shell for语句实战案例
Shell for语句实战案例
for语句实现批量ping ip是否存活
#!/bin/bashfor i in `cat ip_list.txt`do ping -c1 $i -w2 if [ $? -eq 0 ];then echo $i >>success_list.txt else echo $i >>failed_list.txt fi done
for语句批量添加用户
[root@~]# cat create_user.sh #/bin/bashuser_file="user.txt"#如果用户文件存在就备份该文件if [ -f $user_file ];then echo -e "\033[32m${user_file} exit!backup file,rename ${user_file}-$(date +%F).bak \033[0m" \cp $user_file ${user_file}-$(date +%F).bakfiecho "User Password" >> $user_fileecho "---------------">> $user_filefor user_name in user{1..5}do if ! id $user_name &>/dev/null;then #if语句判断判断用户是否存在 passwd=$(echo $RANDOM |md5sum |cut -c 1-8) #产生用户密码然后赋值给变量passwd useradd $user_name echo $passwd | passwd --stdin $user_name &>/dev/null echo "$user_name $passwd">>$user_file echo -e "\033[32mCreate user successful!\033[0m" else echo -e "\033[32m$user_name aleardy Exists! " fi done[root@~]# ./create_user.sh user.txt exit!backup file,rename user.txt-2020-05-13.bak Create user successful!Create user successful!Create user successful!Create user successful!Create user successful![root@~]# cat user.txtUser Password---------------user1 b2f869c2user2 02a7c788user3 9fa9b144user4 bf42fc47user5 3e4073e0
for语句实现批量压缩
[root@tmp]# lsfile1 file2 file3 file4 file5 file6#!/bin/bashcd /tmpfor FILE in `ls` #这个地方也可以写成$(ls),即将ls命令结果当作for的循环池do tar -zcf ${FILE}.tar.gz $FILEdone[root@tmp]# lsfile1 file2 file3 file4 file5 file6file1.tar.gz file2.tar.gz file3.tar.gz file4.tar.gz file5.tar.gz file6.tar.gz
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~