I. Basic concepts

This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging

Shell is a program written in C language, which is the bridge for users to use Linux. Shell is both a command language and a programming language. A Shell is an application that provides an interface through which users can access the services of the operating system kernel. In computer science, a Shell is the software that “provides the user with the interface to do the work”. The Linux shell is a graphical shell interface, and shell scripts refer to scripts that run on the shell.

Two. Basic introduction

1. Basic syntax format and standard

Custom shell scripts are usually placed in /usr/local/sbin to facilitate standard uniformity. Shell scripts usually end in sh, such as test.sh

#! /bin/bash

This is the first shell
date
echo 'Hello world! '
ls
Copy the code

The first line #! /bin/bash must have #! Is a convention flag that tells the system what interpreter is needed to execute the script, which Shell (bash in this case) is used. Echo is used to output text to the window. The text is enclosed in single quotes. The execution result is as follows:

[root@VM-12-14-centos sbin]# sh test.sh 
Wed Aug  4 11:00:46 CST 2021
Hello,word!
test.sh
Copy the code
  • #! /bin/bash Specifies the Shell type to be used by the script as bash.
  • #! Called a sha-bang, or Shebang, Linux analyzes the instruction that follows it and loads it as a parser.
  • Ls is the contents of the script file, indicating that when we execute the hello.sh script, we list the files in the current directory and print Hello World to the console

There are two common ways to execute shell scripts:

  1. If you are not Root, you can add execute permission to the script (because vim editing does not have execute permission by default)
  • Chmod +x test.sh # Add execute permission to the test.sh script
  • Sh # Execute the script in the current directory
  1. Sh The command is executed directly

You can also run the sh -x test.sh command to display the execution process, which helps you troubleshoot script errors

Date “+%Y-%m-%d %H:% m :%S” 2021-08-01 12:25:10 date -d “+1 day” “%Y-%m-%d” + day date -d “-1 year” “% % m – Y % d” minus one year

(1) Basic operator and parameter assignment

  1. $[] : add, subtract, multiply, and divide without adding Spaces
  2. $(()) : add, subtract, multiply, divide, etc., without adding Spaces
#! /bin/bash
a=1
b=2
sum=$[$a+$b]
echo "12345 +$sum"
echo "-- -- -- -- -- -- -- -- -- -- -- --"
echo "First number:"
read  x
echo"The second number:read y
sum=$[$x+$y]
echo "This is the sum of two numbers:$sum"
Copy the code

The execution result is as follows:

[root@VM-12-14-centos sbin]# sh test.sh 2021-08-04 11:44:42 Hello,word! Test. sh 12345+3 ------------ First number: 999 "Second number: 999 This is the sum of two numbers: 1998Copy the code

Read x/a/b/c/d can also be replaced with read -p “string” x/a/b/c/d

read -p "Are the current results satisfactory: Y /N" x
Copy the code

Read -p is equivalent to echo

(2) Conditional judgment statement

The basic condition determination symbols are as follows:

  1. Conditions are used within (()) double parentheses and the available parameter names + >=,<=,>,<,=
  2. Conditions are used in [] square brackets, using -lt (less than), -gt (greater than), -le (less than or equal to), -ge (greater than or equal to), -eq (equal to), and -ne (not equal to).
  3. [] : Spaces must be added around brackets and operators (allowed, not recommended)
  4. [[]] : Spaces must be added around brackets and operators (recommended for string validation)
  5. (()) : Spaces must be added around brackets and operators (recommended for numeric validation)
  6. [[]] and (()) are enhanced versions of [] for mathematical comparison expressions and string expressions, respectively.
  7. Use [[…]] conditionals instead of […] Can prevent many logical errors in the script. For example, &&, | |, <, and > operator can judge condition of normal exists in [[]] structure, but if the words appear in the structure of [], complains. For example, if [[a!= 1 && a!= 2] is used directly. If double parentheses are not used, if [a-ne 1] && [a!= 2] or if [a−ne1− aA-ne 1 -a a−ne1− AA!= 2] is used.
  8. [[]] added pattern matching effect.
  9. (()) no longer needs to escape the size of the symbol in the expression. In addition to the standard mathematical operators, the following symbols can be added

【 1 】 the if

#! /bin/bash
read -p "Please enter your score:" a
if ((a>=60));then
	echo "You passed the grade. Congratulations!"
fi
Copy the code

【2】 If there is a problem

#! /bin/bash
read -p "Please enter your score:" a
if ((a>=60));then
	echo "You passed the grade. Congratulations!"
else
   echo "You failed your grade. Better work next time!"
fi
Copy the code

[3] If there is no one else

#! /bin/bash
read -p "Please enter your score:" a
if ((a>=60)) && ((a<=90));then
   echo "You passed the grade. Congratulations!"
elif ((a>90));then
   echo "Your grades are excellent!"
else
   echo "You failed your grade. Better work next time!"
fi
Copy the code



or



The running results are shown below

[4] Case statement

#! /bin/bash"X a=$[$x%2] case $a in 1) echo" This is an odd number!" ;; 0) echo "This is an even number!" ;; esacCopy the code

Shell Case statements are multi-select statements. A case statement can be used to match a value to a pattern, and if the match is successful, the matching command is executed. Case requires an ESAC (case in reverse) as the closing tag, a close parenthesis for each case branch, and two semicolons for break, where “;;” It’s not breaking out of the loop, it’s not matching the pattern below

  1. Break: Break out of the total loop
  2. Continue: Breaks out of the current loop and continues to the next one

Case scripts are often used to write startup scripts for system services.

[5] the while

# Conditional loop
while condition
do
    command
done

# Infinite loop
while :
do
    command
done
Copy the code

[6] Until loop

The until loop executes a series of commands until it stops when the condition is true. The until loop is the opposite of the while loop.

until condition
do
    command
done
Copy the code

[7] For loop

For variable name in loop condition; do command done

#! /bin/bash
for i in `seq 1 5`;do
        echo $i
done
Copy the code

Seq 1, 5 is a sequence from 1 to 5

(3) Output statements

【 1 】 the echo

It is only recommended for string output echo “” or echo” “

【 2 】 printf

Printf does not automatically add newlines like echo, we can manually add \n without braces, directly separated by Spaces

  • Printf format-string [arguments…] (format-string: format control string, arguments: argument list)
  • Printf “%-10s %-8s %-4.2f\n

%s, %c, %d, %f are all format substitutes:

  1. D: Decimal integer the positional argument must be a Decimal integer.
  2. S: String The position parameter corresponding to the String must be a String or character type. Otherwise, an error is reported
  3. The position parameter corresponding to c: Char must be a string or character type. Otherwise, an error is reported
  4. F: Float Float position parameter must be numeric or an error will be reported
  5. %-10s: a character with a width of 10 characters (- indicates left alignment, and no character indicates right alignment). Any character is displayed within the width of 10 characters. If the value is less than 10 characters, it is automatically filled with Spaces.
  6. %-4.2f: it is formatted as a decimal and has a width of 4 characters.2 indicates that two decimal places are reserved.

Escape character:

  1. \a: warning character, usually the ASCII BEL character
  2. \ b: back
  3. \c: suppress (not show) any ending newline characters in the output (only valid in the argument string controlled by the %b format indicator), and any characters left in the argument, any subsequent arguments, and any characters left in the format string are ignored
  4. \f: Formfeed
  5. \ n: a newline
  6. \ R: Carriage return
  7. \t: Horizontal TAB
  8. \v: Vertical TAB
  9. \ : a literal backslash character
  10. \ DDD: Character representing a 1 – to 3-digit octal value. Valid only in the format string
  11. \0ddd: Octal value character representing 1 to 3 digits

(4) Functions in shell scripts

It is recommended that functions be written at the beginning. Always use $1 for the first argument before the function is called, so that the arguments can be passed in order. Methods can be called from within the script, as well as from outside the script

#! /bin/bash
function add(){
        sum=$[The $1 + $2]
        return $sum
}

add 1 2
echo "Current and: $? !"
Copy the code

And for 3


#! /bin/bash
function add(){
        sum=$[The $1 + $2]
        return $sum
}

add The $1 $2
echo "Current and: $? !"
Copy the code
sh hanshu.sh 3 6
Copy the code

The current sum is: 9!

(5) Common file operations

Shell scripts often use if to determine whether the file is a common file or a directory, and whether the file has read and write execution permission. There are only a few common options:

  • -e: checks whether a file or directory exists
  • -d: checks whether it is a directory and whether it exists
  • -f: checks whether the file is a common file and exists
  • -r: checks whether the document has read permission
  • -w: checks whether the write permission is available
  • -x: checks whether the command can be executed

If is used, the specific format is: if [-e filename]; then

Three. Actual combat entry

1. Get started

(1) the sum of 1 minus 100

#! /bin/bash
a=1
sum=0
b=1
while (($a< = 100)do
        sum=$[$a+$sum]
        a=$[$b+$a]
done

echo $sum 
Copy the code

(2) Input a number, find the sum from 1-n

#bin/bash
sum=0
read -p "Please enter a number:" a
while ((a<1))
do
        read -p "The entered number format is incorrect, please re-enter a number:" a
done

for i in `seq 1 $a`;do
        sum=$[$i+$sum]
done
echo $sum
Copy the code

(3) Copy one directory to another directory

The shell script determines the file directory

Shell scriptsifIt also often makes decisions about the attributes of the file, such as whether it is a normal file or a directory, whether the file has read-write execution permission, and so on. -d: checks whether a file or directory exists. -f: checks whether a file or directory exists. -r: checks whether the file has the read permissionifWhen judging, the specific format is:if [ -e filename ] ; then
Copy the code

#! /bin/bash
cd /home/xt
list=`ls`
for i in ${list[0]}
do
        echo "$i"
        if [ -d $i ];then
           echo "123456"
           cp -r $i /home/test1/
        fi
doneOr * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *#! /bin/bash
for f in `ls /root/`; do
	if [ -d $f];then
		cp -r $f /tmp/
	fi
done
Copy the code

2. File information processing

Awk processes files

#! /bin/bash
awk -F "," '{print NF,$1,$2,$3,$4,$5,$6,$7}' a.txt

awk -F "," '{print NF,$0}' a.txt
Copy the code



Read the file directly and output the data in column 123457

$0 directly outputs all data,

3. Practical scripts

(1) Enable/disable Tomcat

Sh start/stop Start tomcat, log in to tomcat, close Tomcat, determine whether to kill zombie processes, and delete the WAR package in Webapps

#! /bin/bash
tomcat_home=/home/xt/test-tomcat
STARTTOMCAT=$tomcat_home/bin/startup.sh
SHUTDOWN=$tomcat_home/bin/shutdown.sh
WEB=$tomcat_home/webapps
MYLOG=/applog/ossDown-downBatch
TOMCATLOG=$tomcat_home/logs
case The $1 in
start)
        echo "Start Tomcat!"
        $STARTTOMCAT
        cd $TOMCATLOG
        tail -f catalina.out -n 500
        ;;
stop)
        echo "Close Tomcat!"
        $SHUTDOWN
        pid=`ps -ef |grep test-tomcat |grep -v "grep"|awk '{print $2}'`
        if [ "$pid" = "" ];then
                echo "The tomcat thread is currently stopped"
        else
                echo "The closed process id is:$pid"
                kill9 -$pid
        fi
        cd $WEB
        rm -rf *
        ;;

esac
Copy the code