100 out of the box shell scripts, CV method is good, and the work is not brain consuming!

Posted by Poolie on Sun, 30 Jan 2022 13:32:15 +0100

Shell script is a sharp tool to help programmers and system administrators complete time-consuming and laborious boring work. It is an effective way to interact with computers and manage file and system operations. Just a few lines of code can make the computer close to acting according to your intention.

Brother Tian sorted out 100 examples for you. Through 100 actual combat classic script examples, he showed the practical technology and common tool usage of shell script programming. We only need to promote and apply these common tasks and portable automation scripts to other similar problems according to our own needs, which can solve the troubles encountered in three days and two days.

PS: the script file of this article has been sorted into PDF document (I know you like electronic version). See the end of the article for the specific acquisition method.

1. Check the consistency of files in the specified directory of two servers

#!/bin/bash
######################################
Check the consistency of files in the specified directory of two servers
#####################################
#By comparing the md5 value of the files on the two servers, the consistency is detected
dir=/data/web
b_ip=192.168.88.10
#Traverse all the files in the specified directory and use them as parameters of the md5sum command to get the md5 values of all files and write them to the specified file
find $dir -type f|xargs md5sum > /tmp/md5_a.txt
ssh $b_ip "find $dir -type f|xargs md5sum > /tmp/md5_b.txt"
scp $b_ip:/tmp/md5_b.txt /tmp
#Compare file names one by one as traversal objects
for f in `awk '{print 2} /tmp/md5_a.txt'`do
#Taking machine a as the standard, when machine b does not exist, it directly outputs the non-existent result when it traverses the file in the object
if grep -qw "$f" /tmp/md5_b.txt
then
md5_a=`grep -w "$f" /tmp/md5_a.txt|awk '{print $1}'`
md5_b=`grep -w "$f" /tmp/md5_b.txt|awk '{print $1}'`
#When the file exists, if the md5 value is inconsistent, the result of file change will be output
if [ $md5_a != $md5_b ]then
echo "$f changed."
fi
else
echo "$f deleted."
fi
done

2. Clear the file content regularly and record the file size regularly

#!/bin/bash
#################################################################
Execute the script (task plan) every hour. When the time is 0 o'clock or 12 o'clock, all files in the target directory will be saved#The content is empty, but the file is not deleted. At other times, only the size of each file is counted, one file per line, and output to the time#Among the files named by date and date, the files of secondary and tertiary subdirectories under the target directory need to be considered
################################################################
logfile=/tmp/`date +%H-%F`.log
n=`date +%H`
if [ $n -eq 00 ] || [ $n -eq 12 ]
then
#Through the for loop, take the find command as the traversal condition to traverse all files in the target directory and do the corresponding operations
for i in `find /data/log/ -type f`
do
true > $i
done
else
for i in `find /data/log/ -type f`
do
du -sh $i >> $logfile
done
fi

3. Check the network card traffic and record it in the log according to the specified format

#!/bin/bash
#######################################################
#Check the network card traffic and record it in the log according to the specified format#Record once a minute
#The log format is as follows:
#2019-08-12 20:40
#ens33 input: 1234bps
#ens33 output: 1235bps
######################################################3
while :
do
#Set the language to English to ensure that the output result is in English, otherwise there will be a bug
LANG=en
logfile=/tmp/`date +%d`.log
#Redirect the output of the command executed below to the logfile log
exec >> $logfile
date +"%F %H:%M"
#The traffic unit counted by sar command is kb/s, and the log format is bps, so * 1000 * 8 is required
sar -n DEV 1 59|grep Average|grep ens33|awk '{print $2,"\t","input:","\t",$5*1000*8,"bps","\n",$2,"\t","output:","\t",$6*1000*8,"bps"}'
echo "####################"
#Since it takes 59 seconds to execute the sar command, sleep is not required
done

4. Calculate the number of numbers in each line of the document and the total number of numbers in the whole document

#!/bin/bash
#########################################################
#Calculate the number of numbers in each line of the document and the total number of numbers in the whole document
########################################################
#Use awk to output only the number of document lines (intercept the first paragraph)
n=`wc -l a.txt|awk '{print $1}'`
sum=0
#There may be spaces in each line of the document, so you can't traverse directly with the content of the document
for i in `seq 1 $n`do
#When the output line is represented by a variable, double quotation marks are required
line=`sed -n "$i"p a.txt`#wc -L option to count the length of the longest line
n_n=`echo $line|sed s'/[^0-9]//'g|wc -L`
echo $n_nsum=$[$sum+$n_n]
done
echo "sum:$sum"

Kill all scripts

#!/bin/bash
################################################################
#Some scripts have been added to cron, and new tasks need to be executed before the scripts have been run,
#This will increase the system load, so you can write scripts to screen out the processes that affect the load and kill them all at once.
################################################################
ps aux|grep Specify the process name|grep -v grep|awk '{print $2}'|xargs kill -9

5. Download files from FTP server

#!/bin/bash
if [ $# -ne 1 ]; then
    echo "Usage: $0 filename"
fi
dir=$(dirname $1)
file=$(basename $1)
ftp -n -v << EOF   # -n automatic login
open 192.168.1.10  # ftp server
user admin password
binary   # Set ftp transmission mode to binary to avoid different MD5 values or tar.gz compressed package format error
cd $dir
get "$file"
EOF

6. Continuously input 5 numbers within 100, statistics sum, minimum and maximum

#!/bin/bash
COUNT=1
SUM=0
MIN=0
MAX=100
while [ $COUNT -le 5 ]; do
    read -p "Please enter 1-10 Integer:" INT    
    if [[ ! $INT =~ ^[0-9]+$ ]]; then
        echo "The input must be an integer!"
        exit 1
    elif [[ $INT -gt 100 ]]; then
        echo "The input must be within 100!"
        exit 1
    fi
    SUM=$(($SUM+$INT))
    [ $MIN -lt $INT ] && MIN=$INT
    [ $MAX -gt $INT ] && MAX=$INT
    let COUNT++
    done
echo "SUM: $SUM"
echo "MIN: $MIN"
echo "MAX: $MAX

Users guess numbers

#!/bin/bash  # The script generates a random number within 100 and prompts the user to guess the number. According to the user's input, the user is prompted to guess correctly,
# Guess small or big until the user guesses the script correctly.
# RANDOM is a RANDOM number with a value of 0 ‐ 32767
# Use the remainder algorithm to change the random number into a random number of 1-100 num=$[RANDOM%100+1]echo "$num" 
# Use read to prompt the user to guess the number
# Use if to judge the size relationship of the number guessed by the user: - EQ (equal to), - Ne (not equal to), - GT (greater than), - Ge (greater than or equal to),
# - LT (less than), - Le (less than or equal to)

while :
  do     
    read -p "The computer generated a 1‐100 Random number of,Have a guess: " cai    
    if [ $cai -eq $num ]    
    then        
        echo "congratulations,You guessed right"           
        exit        
    elif [ $cai -gt $num ]       
    then            
        echo "Oops,Guess big"         
    else            
        echo "Oops,Guess it's small"     
    fi
  done

7. Monitor the access log 502 of Nginx and take corresponding actions

Assuming that the server environment is lnmp, 502 often occurs in recent visits, and the 502 error disappears after restarting the PHP FPM service. Therefore, it is necessary to write a monitoring script. Once 502 occurs, the PHP FPM service will be restarted automatically.

#Scenario:
#1. Path to log file: / data / log / access log
#2. The script loop is detected every 10 seconds. The number of logs in 10 seconds is 300. If the proportion of 502 is not less than 10% (30), the PHP FPM service needs to be restarted
#3. The restart command is: / etc / init d/php-fpm restart
#!/bin/bash
###########################################################
#Monitor the access log 502 of Nginx and take corresponding actions
###########################################################
log=/data/log/access.log
N=30 #Set threshold
while :do
 #View the latest 300 access logs and count the number of 502
    err=`tail -n 300 $log |grep -c '502" '` 
if [ $err -ge $N ] 
then
/etc/init.d/php-fpm restart 2> /dev/null 
#Set a 60s delay to prevent script bug s from causing unlimited restart of PHP FPM services
     sleep 60
 fi
 sleep 10
 done

8. Assign the results to variables respectively

Application scenario: you want to assign execution results or location parameters to variables for subsequent use.

Method 1:

for i in $(echo "4 5 6"); do
   eval a$i=$idone
echo $a4 $a5 $a6

Method 2: split the position parameter 192.168.1.1 {1,2} into each variable

num=0
for i in $(eval echo $*);do   #eval decomposes {1,2} into 1 and 2
   let num+=1
   eval node${num}="$i"
done
echo $node1 $node2 $node3
# bash a.sh 192.168.1.1{1,2}
192.168.1.11 192.168.1.12

Method 3:

arr=(4 5 6)
INDEX1=$(echo ${arr[0]})
INDEX2=$(echo ${arr[1]})
INDEX3=$(echo ${arr[2]})

9. Batch modify file name

Example:

# touch article_{1..3}.html
# lsarticle_1.html  article_2.html  article_3.html
 Purpose: to article Change to bbs

Method 1:

for file in $(ls *html); do
    mv $file bbs_${file#*_}
    # mv $file $(echo $file |sed -r 's/.*(_.*)/bbs\1/')
    # mv $file $(echo $file |echo bbs_$(cut -d_ -f2)

Method 2:

for file in $(find . -maxdepth 1 -name "*html"); do
     mv $file bbs_${file#*_}done

Method 3:

# rename article bbs *.html
 Delete the lines containing letters in the first five lines of a document, and delete all letters in lines 6 to 10 at the same time

1) Prepare the test file named 2 txt

Line 1 1234567 contains no letters
 Line 2 56789 BBBBBB
 Line 3 67890 CCCCCCCC
 Line 4 78 asdfDDDDDDDDD
 Line 5 123456 EEEEEEEE
 Line 6 1234567 ASDF
 Line 7 56789 ASDF
 Line 8 67890 ASDF
 Line 9 78 asdfADSF
 Line 10 123456 AAAA
 Line 11 67890 ASDF
 Line 12 78 asdfADSF
 Line 13 123456 AAAA

2) The script is as follows:

#!/bin/bash
###############################################################
Delete the lines containing letters in the first five lines of a document, and delete all letters in lines 6 to 10 at the same time
##############################################################
sed -n '1,5'p 2.txt |sed '/[a-zA-Z]/'d
sed -n '6,10'p 2.txt |sed s'/[a-zA-Z]//'g
sed -n '11,$'p 2.txt
#The final result is just the result printed on the screen. If you want to change the file directly, you can write the output result into a temporary file and replace 2 Txt or use the - i option

10. Statistics in the current directory The total size of files at the end of html

Method 1:

# find . -name "*.html" -exec du -k {} \; |awk '{sum+=$1}END{print sum}'

Method 2:

for size in $(ls -l *.html |awk '{print $5}'); do
    sum=$(($sum+$size))
done
echo $sum

11. Scan host port status

#!/bin/bash
HOST=$1
PORT="22 25 80 8080"
for PORT in $PORT; do
    if echo &>/dev/null > /dev/tcp/$HOST/$PORT; then
        echo "$PORT open"
    else
        echo "$PORT close"
    fi
done

Use the shell to print words with less than 6 letters in the sample statement

#Example statement:
#Bash also interprets a number of multi-character options.
#!/bin/bash
##############################################################
#The shell prints words with fewer than 6 letters in the sample statement
##############################################################
for s in Bash also interprets a number of multi-character options.
do
 n=`echo $s|wc -c` 
 if [ $n -lt 6 ] 
 then
 echo $s
 fi
done

12. Enter the number to run the corresponding command

#!/bin/bash
##############################################################
#Enter the number to run the corresponding command
##############################################################
echo "*cmd menu* 1-date 2-ls 3-who 4-pwd 0-exit "
while :
do
#Capture user typed values
 read -p "please input number :" n
 n1=`echo $n|sed s'/[0-9]//'g`
#Null input detection 
 if [ -z "$n" ]
 then
 continue
 fi
#Non digital input detection 
 if [ -n "$n1" ]
 then
 exit 0
 fi
 break
done
case $n in
 1)
 date
 ;;
 2)
 ls
 ;;
 3)
 who
 ;;
 4)
 pwd
 ;;
 0)
 break
 ;;
    #Prompt for entering numbers other than 1-4
 *)
 echo "please input number is [1-4]"
esac

13. Expect realizes SSH interactive free command execution

Expect is a tool for automatic interactive applications, such as telnet, ftp, passwd, etc. You need to install the expect package first.

Method 1: EOF standard output as expect standard input

#!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect << EOFset timeout 30spawn ssh $USER@$IP   expect {    "(yes/no)" {send "yes\r"; exp_continue}    "password:" {send "$PASS\r"}
}
expect "$USER@*"  {send "$1\r"}
expect "$USER@*"  {send "exit\r"}
expect eof
EOF

Method 2:

#!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect -c "
    spawn ssh $USER@$IP
    expect {
        \"(yes/no)\" {send \"yes\r\"; exp_continue}
        \"password:\" {send \"$PASS\r\"; exp_continue}
        \"$USER@*\" {send \"df -h\r exit\r\"; exp_continue}
    }"

Method 3: separate the expect script

Login script:
# cat login.exp
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set cmd [lindex $argv 3]
if { $argc != 4 } {
puts "Usage: expect login.exp ip user passwd"
exit 1
}
set timeout 30
spawn ssh $user@$ip
expect {    
    "(yes/no)" {send "yes\r"; exp_continue}
    "password:" {send "$passwd\r"}
}
expect "$user@*"  {send "$cmd\r"}
expect "$user@*"  {send "exit\r"}
expect eof

Execute command script: write a cycle to operate multiple servers in batch

#!/bin/bash
HOST_INFO=user_info.txt
for ip in $(awk '{print $1}' $HOST_INFO)
do
    user=$(awk -v I="$ip" 'I==$1{print $2}' $HOST_INFO)
    pass=$(awk -v I="$ip" 'I==$1{print $3}' $HOST_INFO)
    expect login.exp $ip $user $pass $1
done

SSH connection information of Linux host:

# cat user_info.txt
192.168.1.120 root 123456

Create 10 users and set their passwords respectively. The password requires 10 digits and contains upper and lower case letters and numbers. Finally, the password of each user needs to be stored in the specified file

#!/bin/bash
##############################################################
#Create 10 users and set passwords respectively. The password requires 10 digits and contains upper and lower case letters and numbers
#Finally, the password of each user needs to be stored in the specified file#Prerequisite: install mkpasswd command
##############################################################
#Generate a sequence of 10 users (00-09)
for u in `seq -w 0 09`do
 #Create user
 useradd user_$u
 #Generate password
 p=`mkpasswd -s 0 -l 10` 
 #Read the password from the standard input and modify it (unsafe)
 echo $p|passwd --stdin user_$u
 #General password modification
 echo -e "$p\n$p"|passwd user_$u
 #Record the created user and the corresponding password in the log file
 echo "user_$u $p" >> /tmp/userpassworddone

14. Monitor the number of httpd processes and handle them accordingly according to the monitoring situation

#!/bin/bash
###############################################################################################################################
#Requirements:
#1. Monitor the number of httpd processes every 10s. If the number of processes is greater than or equal to 500, the Apache service will be restarted automatically, and check whether the service is restarted successfully
#2. If it fails, it needs to be started again. If it still fails to restart five times, it will send an alarm email to the administrator and exit the detection
#3. If the startup is successful, wait for 1 minute and check the number of httpd processes again. If the number of processes is normal, restore the normal detection (once every 10s). Otherwise, give up the restart, send an alarm email to the administrator and exit the detection
###############################################################################################################################
#Counter function
check_service()
{
 j=0
 for i in `seq 1 5` 
 do
 #Command to restart Apache
 /usr/local/apache2/bin/apachectl restart 2> /var/log/httpderr.log    
    #Judge whether the service is restarted successfully
 if [ $? -eq 0 ] then
 break
 else
 j=$[$j+1] fi
    #Determine whether the service has tried to restart 5 times
 if [ $j -eq 5 ] then
 mail.py exit
 fi
 done }while :do
 n=`pgrep -l httpd|wc -l` 
 #Determine whether the number of httpd service processes exceeds 500
 if [ $n -gt 500 ] then
 /usr/local/apache2/bin/apachectl restart 
 if [ $? -ne 0 ] 
 then
 check_service 
 else
 sleep 60
 n2=`pgrep -l httpd|wc -l` 
 #Judge whether it still exceeds 500 after restart
             if [ $n2 -gt 500 ] 
 then 
 mail.py exit
 fi
 fi
 fi
 #Test every 10s
 sleep 10done

15. Batch modify server user password

SSH connection information of Linux host: old password

# cat old_pass.txt 
192.168.18.217  root    123456     22
192.168.18.218  root    123456     22
 Content format: IP User Password Port

SSH Remote password modification script: random generation of new password

#!/bin/bash
OLD_INFO=old_pass.txt
NEW_INFO=new_pass.txt
for IP in $(awk '/^[^#]/{print $1}' $OLD_INFO); do
    USER=$(awk -v I=$IP 'I==$1{print $2}' $OLD_INFO)
    PASS=$(awk -v I=$IP 'I==$1{print $3}' $OLD_INFO)
    PORT=$(awk -v I=$IP 'I==$1{print $4}' $OLD_INFO)
    NEW_PASS=$(mkpasswd -l 8)  # Random password
    echo "$IP   $USER   $NEW_PASS   $PORT" >> $NEW_INFO
    expect -c "
    spawn ssh -p$PORT $USER@$IP
    set timeout 2
    expect {
        \"(yes/no)\" {send \"yes\r\";exp_continue}
        \"password:\" {send \"$PASS\r\";exp_continue}
        \"$USER@*\" {send \"echo \'$NEW_PASS\' |passwd --stdin $USER\r exit\r\";exp_continue}
    }"
done

Generate new password file:

# cat new_pass.txt 
192.168.18.217  root    n8wX3mU%      22
192.168.18.218  root    c87;ZnnL      22

16. iptables automatically blocks IP addresses that frequently visit websites
Scenario: malicious access, security precautions

1) Mask access to more than 200 IP S per minute
Method 1: according to the access log (Nginx as an example)

#!/bin/bash
DATE=$(date +%d/%b/%Y:%H:%M)
ABNORMAL_IP=$(tail -n5000 access.log |grep $DATE |awk '{a[$1]++}END{for(i in a)if(a[i]>100)print i}')
#First, tail to prevent the file from being too large and slow to read. The number can adjust the maximum access per minute. awk cannot filter logs directly because it contains special characters.
for IP in $ABNORMAL_IP; do
    if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
        iptables -I INPUT -s $IP -j DROP    fidone

Method 2: connect via TCP

#!/bin/bash
ABNORMAL_IP=$(netstat -an |awk '$4~/:80$/ && $6~/ESTABLISHED/{gsub(/:[0-9]+/,"",$5);{a[$5]++}}END{for(i in a)if(a[i]>100)print i}')
#gsub is to remove the colon and port in the fifth column (client IP)
for IP in $ABNORMAL_IP; do
    if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
        iptables -I INPUT -s $IP -j DROP    
        fi
done

2) Mask the IP with more than 10 SSH login attempts per minute
Method 1: obtain login status through lastb:

#!/bin/bash
DATE=$(date +"%a %b %e %H:%M") #On Sunday, month and Sunday, when% e is a single number, 7 is displayed, while% d shows 07
ABNORMAL_IP=$(lastb |grep "$DATE" |awk '{a[$3]++}END{for(i in a)if(a[i]>10)print i}')for IP in $ABNORMAL_IP; do
    if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
        iptables -I INPUT -s $IP -j DROP    fidone

Method 2: get login status through log

#!/bin/bash
DATE=$(date +"%b %d %H")
ABNORMAL_IP="$(tail -n10000 /var/log/auth.log |grep "$DATE" |awk '/Failed/{a[$(NF-3)]++}END{for(i in a)if(a[i]>5)print i}')"
for IP in $ABNORMAL_IP; do
    if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
        iptables -A INPUT -s $IP -j DROP        
        echo "$(date +"%F %T") - iptables -A INPUT -s $IP -j DROP" >>~/ssh-login-limit.log    
    fi
done

17. According to the web access log, the IP with abnormal blocking requests will be unblocked if the IP returns to normal after half an hour

#!/bin/bash
####################################################################################
#According to the web access log, the IP with abnormal blocking requests will be unblocked if the IP returns to normal after half an hour
####################################################################################
logfile=/data/log/access.log
#Displays the hours and minutes one minute ago
d1=`date -d "-1 minute" +%H%M`
d2=`date +%M`
ipt=/sbin/iptables
ips=/tmp/ips.txt
block()
{ 
#Filter out all the logs one minute ago, extract the IP and count the number of accesses
 grep '$d1:' $logfile|awk '{print $1}'|sort -n|uniq -c|sort -n > $ips
 #Use the for loop to traverse the IP with more than 100 times in turn and block it
 for i in `awk '$1>100 {print $2}' $ips` 
 do
 $ipt -I INPUT -p tcp --dport 80 -s $i -j REJECT 
 echo "`date +%F-%T` $i" >> /tmp/badip.log 
 done
}
unblock()
{ 
#The IP with less than 10 pkts generated after blocking will be traversed and unsealed in turn
 for a in `$ipt -nvL INPUT --line-numbers |grep '0.0.0.0/0'|awk '$2<10 {print $1}'|sort -nr` 
 do 
 $ipt -D INPUT $a
 done
 $ipt -Z
}
#The unpacking function is executed at 00 and 30 minutes
if [ $d2 -eq "00" ] || [ $d2 -eq "30" ] 
 then
 #It is necessary to unlock and then seal, because the number of pkts generated when the ban is just closed is very small
 unblock
 block 
 else
 block
fi

18. Judge whether the IP address entered by the user is IP address

Method 1:

#!/bin/bash
function check_ip(){
    IP=$1
    VALID_CHECK=$(echo $IP|awk -F. '$1< =255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
    if echo $IP|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$">/dev/null; then
        if [ $VALID_CHECK == "yes" ]; then
            echo "$IP available."
        else
            echo "$IP not available!"
        fi
    else
        echo "Format error!"
    fi
}
check_ip 192.168.1.1
check_ip 256.1.1.1

Method 2:

#!/bin/bash
function check_ip(){
    IP=$1
    if [[ $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        FIELD1=$(echo $IP|cut -d. -f1)
        FIELD2=$(echo $IP|cut -d. -f2)
        FIELD3=$(echo $IP|cut -d. -f3)
        FIELD4=$(echo $IP|cut -d. -f4)
        if [ $FIELD1 -le 255 -a $FIELD2 -le 255 -a $FIELD3 -le 255 -a $FIELD4 -le 255 ]; then
            echo "$IP available."
        else
            echo "$IP not available!"
        fi
    else
        echo "Format error!"
    fi
}
check_ip 192.168.1.1
check_ip 256.1.1.1

Added version:
Add an endless loop. If the IP is available, exit. If it is not available, prompt to continue to enter, and use awk to judge.

#!/bin/bash
function check_ip(){
    local IP=$1
    VALID_CHECK=$(echo $IP|awk -F. '$1< =255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
    if echo $IP|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" >/dev/null; then
        if [ $VALID_CHECK == "yes" ]; then
            return 0
        else
            echo "$IP not available!"
            return 1
        fi
    else
        echo "Format error! Please input again."
        return 1
    fi
}
while true; do
    read -p "Please enter IP: " IP
    check_ip $IP
    [ $? -eq 0 ] && break || continue
done

19. Judge whether the number entered by the user is a number
Method 1:

#!/bin/bash
if [[ $1 =~ ^[0-9]+$ ]]; then
    echo "Is Number."
else
    echo "No Number."
fi

Method 2:

#!/bin/bash
if [ $1 -gt 0 ] 2>/dev/null; then
    echo "Is Number."
else
    echo "No Number."
fi

Method 3:

#!/bin/bash
echo $1 |awk '{print $0~/^[0-9]+$/?"Is Number.":"No Number."}'  #ternary operator 
12.14 Find the file that contains the keyword
DIR=$1
KEY=$2
for FILE in $(find $DIR -type f); do
    if grep $KEY $FILE &>/dev/null; then
        echo "--> $FILE"
    fi
done

20. Monitor the directory and append the newly created file name to the log

Scenario: record the file operation in the directory. You need to install inotify tools package first.

#!/bin/bash
MON_DIR=/opt
inotifywait -mq --format %f -e create $MON_DIR |\
while read files; do
  echo $files >> test.log
done

21. Provide users with multiple network card options

Scenario: when the server has multiple network cards, obtain the specified network card, such as network card traffic

#!/bin/bash
function local_nic() {
    local NUM ARRAY_LENGTH
    NUM=0
    for NIC_NAME in $(ls /sys/class/net|grep -vE "lo|docker0"); do
        NIC_IP=$(ifconfig $NIC_NAME |awk -F'[: ]+' '/inet addr/{print $4}')
        if [ -n "$NIC_IP" ]; then
            NIC_IP_ARRAY[$NUM]="$NIC_NAME:$NIC_IP"    #Put the network card name and corresponding IP into the array
            let NUM++
        fi
    done
    ARRAY_LENGTH=${#NIC_IP_ARRAY[*]}
    if [ $ARRAY_LENGTH -eq 1 ]; then     #If there is only one record in the array, it indicates a network card
        NIC=${NIC_IP_ARRAY[0]%:*}
        return 0
    elif [ $ARRAY_LENGTH -eq 0 ]; then   #If there is no record, there is no network card
        echo "No available network card!"
        exit 1
    else
        #If there are multiple records, you will be prompted to enter and select
        for NIC in ${NIC_IP_ARRAY[*]}; do
            echo $NIC
        done
        while true; do
            read -p "Please enter local use to network card name: " INPUT_NIC_NAME
            COUNT=0
            for NIC in ${NIC_IP_ARRAY[*]}; do
                NIC_NAME=${NIC%:*}
                if [ $NIC_NAME == "$INPUT_NIC_NAME" ]; then
                    NIC=${NIC_IP_ARRAY[$COUNT]%:*}
                    return 0
                else
                   COUNT+=1
                fi
            done
            echo "Not match! Please input again."
        done
    fi
}
local_nic

22. MySQL database backup

#!/bin/bash
DATE=$(date +%F_%H-%M-%S)
HOST=192.168.1.120
DB=test
USER=bak
PASS=123456
MAIL="zhangsan@example.com lisi@example.com"
BACKUP_DIR=/data/db_backup
SQL_FILE=${DB}_full_$DATE.sql
BAK_FILE=${DB}_full_$DATE.zip
cd $BACKUP_DIR
if mysqldump -h$HOST -u$USER -p$PASS --single-transaction --routines --triggers -B $DB > $SQL_FILE; then
    zip $BAK_FILE $SQL_FILE && rm -f $SQL_FILE
    if [ ! -s $BAK_FILE ]; then
            echo "$DATE content" | mail -s "theme" $MAIL
    fi
else
    echo "$DATE content" | mail -s "theme" $MAIL
fi
find $BACKUP_DIR -name '*.zip' -ctime +14 -exec rm {} \;

Due to the limited space, only 22 scripts are listed here, but I have sorted out 100 practical shell scripts into a PDF,
Share it for free. Just click to get it.

Finally, I've seen this. Would you please give me a compliment and pay attention?

Previous hot articles:

end

Topics: Java shell