34 commonly used Linux Shell scripts will definitely help you!

As a Linux engineer, being able to write good scripts can not only improve your work efficiency, but also give you more time to do your own things. When I was surfing the Internet recently, I also paid attention to collecting some scripts written by big guys, and summarized them. Welcome to collect them, and share with you!

(1) The user guesses the number

 
 

#!/bin/bash

# The script generates a random number within 100, prompts the user to guess the number, according to the user's input, prompts the user to guess correctly,
# guess small or big, until the user guesses correctly, the script ends.

# RANDOM is a system variable that comes with the system, the value is a random number 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 user's guessed number: -eq (equal), -ne (not equal), -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 random number of 1‐100, you guessed: " cai  
    if [ $cai -eq $num ]   
    then     
        echo "Congratulations, you guessed it"     
        exit  
     elif [ $cai -gt $num ]  
     then       
            echo "Oops, guess big"    
       else      
            echo "Oops, 

(2) Check how many remote IPs are connecting to this machine

 
 

#!/bin/bash

#!/bin/bash
# Check how many remote IPs are connecting to this machine (whether it is through ssh, web or ftp) 

# Use netstat ‐atn to view the status of all connections on this machine,‐ a View all,
# -t only display tcp connection information, ‐n number format displays
# Local Address (the fourth column is the IP and port information of the machine)
# Foreign Address (the fifth column is the IP and port information of the remote host )
# Use the awk command to display only the data in column 5, and then display the information of the IP address in column 1
# sort can be sorted by number, and finally use uniq to delete redundant duplicates and count the number of duplicates
netstat -atn | awk '{ print $5}' | awk '{print $1}' | sort -nr | uniq -c

(3)helloworld

 
 

#!/bin/bash

function example {
echo "Hello world!"
}
example

(4) Print the pid of tomcat

 
 

#!/bin/sh`

v1="Hello"
v2="world"
v3=${v1}${v2}
echo $v3

pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'`
echo $pidlist
echo "tomcat Id list :$pidlist"  //显示pid

(5) Scripting a rock-paper-scissors game

 
 

#!/bin/bash

game=(rock paper scissors)
num=$[RANDOM%3]
computer=${game[$sum]}

echo "Please choose your punching gesture according to the following tips"
echo "1. Rock"
echo " 2. Scissors"
echo " 3.cloth "

read -p "please select 1-3:" person
case $person in
1)
  if [ $num -eq 0 ]
  then 
    echo "tie"
    elif [ $num -eq 1 ]
    then
      echo "you win"
    else 
      echo " computer wins"
fi;;
2)
 if [ $num -eq 0 ]
 then
    echo "computer wins"
    elif [ $num -eq 1 ] 
    then
     echo "tie"
    else 
      echo "you win"
fi;;
3)
 if [ $num -eq 0 ]
 then  
   echo "You win"
   elif [ $num -eq 1 ]
   then 
     echo "Computer wins"
   else 
      echo "Tie"
fi;;
*)
  echo "A number from 1-3 must be entered"
esac

(6) Ninety-nine multiplication table

 
 

#!/bin/bash

for i in `seq 9`
do 
 for j in `seq $i`
 do 
 echo -n "$j*$i=$[i*j] "
 done
    echo
done

(7) The script uses source code to install the memcached server

 
 

#!/bin/bash
# One-click deployment memcached 

# Script uses source code to install memcached server
# Note: If the download link of the software expires, please update the download link of memcached
wget http://www.memcached.org/files/memcached -1.5.1.tar.gz
yum -y install gcc
tar -xf memcached‐1.5.1.tar.gz
cd memcached‐1.5.1
./configure
make
make install

(8) Detect whether the current user of this machine is a super administrator

 
 

#!/bin/bash

# Detect whether the current user of this machine is a super administrator. If it is an administrator, use yum to install vsftpd. If not #
Yes, it will prompt you to be a non-administrator (use a string to compare the version) 
if [ $ USER == "root" ] 
then 
 yum -y install vsftpd
else 
 echo "You are not an administrator and do not have permission to install software"
fi

(9) if operation expression

 
 

#!/bin/bash -xv

if [ $1 -eq 2 ] ;then
 echo "wo ai wenmin"
elif [ $1 -eq 3 ] ;then 
 echo "wo ai wenxing "
elif [ $1 -eq 4 ] ;then 
 echo "wo de xin "
elif [ $1 -eq 5 ] ;then
 echo "wo de ai "
fi

(10) The script kills the tomcat process and restarts

 
 

#!/bin/bash

#kill tomcat pid

pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'` #find the PID number of tomcat echo "

tomcat Id list :$pidlist" //Display pid

kill -9 $pidlist #Kill the improved process

echo "KILL $pidlist:" //Prompt the process and be killed

echo "service stop success"

echo "start tomcat"

cd /opt/ apache-tomcat-7.0.75

pwd 

rm -rf work/*

cd bin

./startup.sh #;tail -f ../logs/catalina.out

(11) Print the chess board

 
 

#!/bin/bash
# Print Chessboard
# Set two variables, i and j, one represents row, one represents column, chess is 8*8 chessboard
# i=1 is ready to print the first row of chessboard, the first row 1-row checkerboard has gray and blue spaced output, 8 columns in total
# i=1,j=1 represents column 1 of row 1; i=2,j=3 represents column 3 of row 2
# of the checkerboard The rule is that if i+j is an even number, print a blue color block, and if it is an odd number, print a gray color block
# Use echo -ne to print a color block, and the line will not automatically wrap after the color block is printed, and continue to output other color blocks on the same line
for i in {1..8}
do
   for j in {1..8}
   do
    sum=$[i+j]
  if [ $[sum%2] -eq 0 ];then
    echo -ne "\033[46m \033[0m"
  else
   echo -ne "\033[47m \033[0m"
  fi
   done
   echo
done
 

(12) Count the number of accounts that can log in to the computer in the current Linux system

 
 

#!/bin/bash

# Count the number of accounts that can log in to the computer in the current Linux system
#Method 1:
grep "bash$" /etc/passwd | wc -l
#Method 2:
awk -f : '/bash$/ {x++}end{print x}' /etc/passwd

(13) Backup MySQL table data

 
 

#!/bin/sh

source /etc/profile
dbName=mysql
tableName=db
echo [`date +'%Y-%m-%d %H:%M:%S'`]' start loading data...'
mysql -uroot -proot -P3306 ${dbName} -e "LOAD DATA LOCAL INFILE '# /home/wenmin/wenxing.txt' INTO TABLE ${tableName} FIELDS TERMINATED BY ';'"
echo [`date +'%Y-%m-%d %H:%M:%S'`]' end loading data...'
exit
EOF

(14) Use an infinite loop to display the packet traffic sent by the eth0 network card in real time

 
 

#!/bin/bash

# Use an infinite loop to display the data packet traffic sent by the eth0 network card in real time 

while:
do 
 echo 'The traffic information of the local network card ens33 is as follows:'
 ifconfig ens33 | grep "RX pack" | awk '{print $5}'
     ifconfig ens33 | grep "TX pack" | awk '{print $5}'
 sleep 1
done

(15) Write a script to test which hosts in the entire network segment of 192.168.4.0/24 are powered on and which hosts are powered off

 
 

#!/bin/bash

# Write a script to test which hosts in the entire network segment of 192.168.4.0/24 are on and which hosts are off
# Status (for version)
for i in {1..254}
do 
 # Every 0.3 seconds Ping once, ping 2 times in total, and set the timeout time of ping in units of 1 millisecond
 ping -c 2 -i 0.3 -W 1 192.168.1.$i &>/dev/null
     if [ $? -eq 0 ];then
 echo "192.168.1.$i is up"
 else 
 echo "192.168.1.$i is down"
 fi
done

(16) Write script: Prompt the user to enter the user name and password, and the script will automatically create the corresponding account and configure the password. if the user

 
 

#!/bin/bash
# Write a script: Prompt the user to enter the user name and password, and the script will automatically create the corresponding account and configure the password. If the user # does not enter the account name, it will prompt that the account name must be entered and exit the script; if the user does not enter the password, the default # default 123456
will be used uniformly as the default password. read -p "Please enter the user name:" user #Use -z to judge whether a variable is empty, if it is empty, prompt the user to enter the account name, and exit the script, the exit code is 2 #No user name entered after the script exits , use $? to check the return code is 2 if [ -z $user ]; then  echo "You do not need to enter the account name"   exit 2 fi  #Use stty -echo to close the echo function of the shell #Use stty echo to open the echo of the shell Display function stty -echo  read -p "Please enter the password:" pass stty echo  pass=${pass:-123456} useradd "$user" echo "$pass" | passwd --stdin "$user"
















(17) Use the script to sort the three input integers

 
 
 
 

#!/bin/bash

# Prompt the user to input 3 integers in turn, and the script will sort and output 3 numbers according to the size of the numbers
read -p " Please enter an integer: " num1
read -p " Please enter an integer: " num2
read -p " Please enter an integer: " num3

# No matter who is big or small, it will be printed at the end echo "$num1,$num2,$num3" # The
smallest value is always stored in num1, the middle value is always stored in num2, and the maximum value is always stored in num3
# If the input is not in this order, change the storage order of the numbers, for example: you can swap the values ​​of num1 and num2
tmp=0
# If num1 is greater than num2, swap the values ​​of num1 and num2 to ensure that the num1 variable is stored is the minimum value
if [ $num1 -gt $num2 ]; then
 tmp=$num1
 num1=$num2
 num2=tmp
fi
# If num1 is greater than num3, swap num1 and num3 to ensure that the minimum value is stored in the num1 variable
if [ $num1 -gt $num3 ];then
 tmp=$num1
 num1=$num3
 num3=$tmp
fi
# If num2 is greater than num3, swap num2 and num3 to ensure that the minimum value is stored in the num2 variable
if [ $num2 -gt $num3 ];then
 tmp=$num2
 num2=$num3
 num3=$tmp
fi
echo "The sorted data (from small to large) is: $num1,$num2,$num3"

(18) According to the current time of the computer, the greeting is returned, and the script can be set to start at boot

 
 

#!/bin/bash
# According to the current time of the computer, return the greeting, you can set the script to boot 

# 00-12 o'clock is morning, 12-18 o'clock is afternoon, 18-24 o'clock is evening
# Use the date command to get After the time, if judges the time interval and determines the greeting content
tm=$(date +%H)
if [ $tm -le 12 ];then
 msg="Good Morning $USER"
elif [ $tm -gt 12 -a $ tm -le 18 ];then
   msg="Good Afternoon $USER"
else
   msg="Good Night $USER"
fi
echo "The current time is: $(date +"%Y‐%m‐%d %H:%M: %S")"
echo -e "\033[34m$msg\033[0m"

(19) Write I lov cls to the txt file

 
 

#!/bin/bash

cd /home/wenmin/
touch wenxing.txt
echo "I lov cls" >>wenxing.txt

(20) Script writing for loop judgment

 
 

#!/bin/bash

s=0;
for((i=1;i<100;i++))
do 
 s=$[$s+$i]
done 

echo $s

r=0;
a=0;
b=0;
for((x=1;x<9;x++))
do 
 a=$[$a+$x] 
echo $x
done
for((y=1;y<9;y++))
do 
 b=$[$b+$y]
echo $y

done

echo $r=$[$a+$b]

(21) Script writing for loop judgment

 
 

#!/bin/bash

for i in "$*"
do 
 echo "wenmin xihuan $i"
done

for j in "$@"
do 
 echo "wenmin xihuan $j"
done

(22) The script uses the tar command to back up all log files under /var/log every 5 weeks

 
 

#!/bin/bash
# Use the tar command to back up all log files under /var/log every 5 days
# vim /root/logbak.sh
# Write a backup script, the file name after backup contains a date label to prevent subsequent backups from being The previous backup data is overwritten
# Note that the date command needs to be enclosed in backticks, and the backticks are on the keyboard <tab> key

tar -czf log-`date +%Y%m%d`.tar.gz /var/log 

# crontab -e #Write scheduled tasks and execute backup scripts
00 03 * * 5 /home/wenmin/datas/logbak.sh

(23) Scripting summation function operation function xx()

 
 

#!/bin/bash

function sum()
{
 s=0;
 s=$[$1+$2]
 echo $s
}
read -p "input your parameter " p1
read -p "input your parameter " p2

sum $p1 $p2

function multi()
{
 r=0;
 r=$[$1/$2]
 echo $r
}
read -p "input your parameter " x1
read -p "input your parameter " x2

multi $x1 $x2

v1=1
v2=2
let v3=$v1+$v2
echo $v3

(24) Scripting case — esac branch structure expression

 
 

#!/bin/bash 

case $1 in 
1) 
 echo "wenmin "
;;
2)
 echo "wenxing "
;; 
3)  
 echo "wemchang "
;;
4) 
 echo "yijun"
;;
5)
 echo "sinian"
;;
6)  
 echo "sikeng"
;;
7) 
 echo "yanna"
;;
*)
 echo "danlian"
;; 
esac

(25) # Define the address of the page to be monitored, restart or maintain the tomcat status

 
 

#!/bin/sh  
# function: Automatically monitor the tomcat process, and restart it if it hangs up  
# author:huanghong  
# DEFINE  

# Get tomcat PPID  
TomcatID=$(ps -ef |grep tomcat |grep -w 'apache-tomcat-7.0 .75'|grep -v 'grep'|awk '{print $2}')  

# tomcat_startup  
StartTomcat=/opt/apache-tomcat-7.0.75/bin/startup.sh  


#TomcatCache=/usr/apache-tomcat-5.5 .23/work  

# Define the page address to be monitored  
WebUrl=http://192.168.254.118:8080/

# Log output  
GetPageInfo=/dev/null  
TomcatMonitorLog=/tmp/TomcatMonitor.log  

Monitor()  
  {  
   echo "[info] start Monitor tomcat...[$(date +'%F %H:%M:%S')]"  
   if [ $TomcatID ]
 then  
      echo "[info]The tomcat process ID is: $TomcatID.  "  
      # Get the return status code  
      TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code})  
      if [ $TomcatServiceCode -eq 200 ];then  
          echo "[info] returns The code is $TomcatServiceCode, tomcat starts successfully, and the page is normal."  
      else  
          echo "[error] There is an access error, the status code is $TomcatServiceCode, and the error log has been output to $GetPageInfo"  
          echo "[error] Restart tomcat"  
          kill -9 $TomcatID # Kill the original tomcat process  
          sleep 3  
          #rm -rf $TomcatCache # Clean up tomcat cache  
          $StartTomcat  
      fi  
      else  
      echo "[error] process does not exist! Tomcat restarts automatically..."  
      echo "[info]$StartTomcat, please wait. .....  "  
      #rm -rf $TomcatCache  
      $StartTomcat  
    fi  
    echo "------------------------------"  
   }  
   Monitor>>$TomcatMonitorLog

(26) Create a Linux system account and password through location variables

 
 

#!/bin/bash

# Create Linux system account and password through location variables

# $1 is the first parameter to execute the script, $2 is the second parameter to execute the script

useradd "$1"
echo "$2" | passwd --stdin " $1"

(27) Pass in and get the number of variables and print

 
 

#!/bin/bash
echo "$0 $1 $2 $3" // Pass in three parameters
echo $# //Get the number of incoming parameters
echo $@ //Print and get the incoming parameters
echo $* //Print and get the incoming parameters parameter

(28) Real-time monitoring of the local memory and the remaining space of the hard disk. When the remaining memory is less than 500M and the remaining space of the root partition is less than 1000M, an alarm email will be sent to the root administrator

 
 

#!/bin/bash

# Real-time monitoring of the remaining space of the local memory and hard disk, when the remaining memory is less than 500M, and the remaining space of the root partition is less than 1000M, an alarm email will be sent to the root administrator # Extract the remaining space of the root partition

disk_size
=$(df / | awk '/\//{print $4}')

# Extract the remaining empty space in the memory
mem_size=$(free | awk '/Mem/{print $4}')
while :
do 
# Note that the size of the memory and disk extraction space is based on Kb is the unit
if [ $disk_size -le 512000 -a $mem_size -le 1024000 ]
then
    mail ‐s "Warning" root <<EOF
 Insufficient resources, insufficient resources
EOF
fi
done

(29) Check whether the corresponding file exists in the specified directory

 
 

#!/bin/bash

if [ -f /home/wenmin/datas ]
then 
echo "File exists"
fi

(30) Script definition while loop statement

 
 

#!/bin/bash

if [ -f /home/wenmin/datas ]
then 
echo "File exists"
fi

[root@rich datas]# cat while.sh 
#!/bin/bash

s=0
i=1
while [ $i -le 100 ]
do
        s=$[$s + $i]
        i=$[$i + 1]
done

echo $s
echo $i

(31) One-click deployment of LNMP (RPM package version)

 
 

#!/bin/bash 

# One-click deployment of LNMP (RPM package version)
# Use yum to install and deploy LNMP, you need to configure the yum source in advance, otherwise the script will fail
# This script is used for centos7.2 or RHEL7.2
yum -y install httpd
yum -y install mariadb mariadb-devel mariadb-server
yum -y install php php-mysql

systemctl start httpd mariadb
systemctl enable httpd mariadb

(32) Read the incoming parameters of the console

 
 

#!/bin/bash
read -t 7 -p "input your name " NAME
echo $NAME

read -t 11 -p "input you age " AGE
echo $AGE

read -t 15 -p "input your friend " FRIEND
echo $FRIEND

read -t 16 -p "input your love " LOVE
echo $LOVE

(33) Script realizes copying

 
 

#!/bin/bash

cp $1 $2

(34) The script realizes the judgment of whether the file exists or not

 
 

#!/bin/bash

if [ -f file.txt ];then
 echo "file exists"
else 
 echo "file does not exist"
fi

 

Guess you like

Origin blog.csdn.net/2301_77463738/article/details/131603916