An example of shell script to count file size and create users in batch

Time:2020-9-15

Statistics file size

Demand:

The script is executed once an hour. When the time is 0 o’clock or 12 o’clock, the contents of all log files in the / data / logs directory (including the files in the subdirectories of the directory) are cleared. At other times, the size of each file is counted, and a file is recorded into the file named with date and time

#!/bin/bash
dir=/data/log_size
logdir=/data/logs
d=`date +%d%H`
t=`date +%H`
#When the directory does not exist, create a record file storage directory
[ -d $dir ] || mkdir $dir
#When the record file exists, delete it first (avoid recording to the record file of last month)
[ -f $dir/$d.log ] && rm -f $dir/$d.log
#When the time is 0 or 12 o'clock, the contents of all log files are cleared
if [ $t == "00" -o $t == "12" ]
then
  for f in `find $logdir -type f`
  do
    > $f
  done
#When the time is not 0 or 12 o'clock, record the size of each file
else
  for f in `find $logdir -type f`
  do
    du -sh $f >> $dir/$d.log
  done
fi

Create users in batch

Demand:

Create 10 users in batch, and the password requires 10 digits: including case and number. The password of each user needs to be recorded in a file

#!/bin/bash
for i in `seq -w 1 10`
do
 useradd user$i
 #Generate random password, no special symbol, length 10
 p=`mkpasswd -s 0 -l 10`
 #Record the user name and password
 echo "user$i $p" >> /tmp/user.passwd
 #Create password
 echo $p |passwd --stdin user$i
done

Implementation effect:

[[email protected] ~]# sh create_users.sh
Change the password of user user01.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user02.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user03.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user04.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user05.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user06.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user07.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user08.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user09.
Passwd: all authentication tokens have been successfully updated.
Change the password of user user10.
Passwd: all authentication tokens have been successfully updated.
[[email protected] ~]# cat /tmp/user.passwd
user01 usgxQ8tM6c
user02 D6iKma5lep
user03 Ubf32wdGqn
user04 iskVwfRi13
user05 mby2Xm3dwM
user06 ehkq5eNDi1
user07 yvmlXTpk79
user08 m15keaGigZ
user09 lx1fxvF7eQ
user10 MhcyjEc27v

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.