code学习

Shell for语句实战案例

for语句实现批量ping ip是否存活

#!/bin/bash
for 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@www ~]# cat create_user.sh 
#/bin/bash
user_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).bak
fi

echo  "User Password" >> $user_file
echo "---------------">> $user_file

for 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@www ~]# ./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@www ~]# cat user.txt
User Password
---------------
user1   b2f869c2
user2   02a7c788
user3   9fa9b144
user4   bf42fc47
user5   3e4073e0      

for语句实现批量压缩

[root@www tmp]# ls
file1  file2  file3  file4  file5  file6

#!/bin/bash
cd /tmp
for FILE in `ls`   #这个地方也可以写成$(ls),即将ls命令结果当作for的循环池
do
        tar -zcf ${FILE}.tar.gz $FILE
done

[root@www tmp]# ls
file1         file2         file3         file4         file5         file6
file1.tar.gz  file2.tar.gz  file3.tar.gz  file4.tar.gz  file5.tar.gz  file6.tar.gz