Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

This paper has participated inProject DigginTo win the creative gift package and challenge the creative incentive money.

preface

Shell is one of the programming languages. Compared with other high-level languages, shell is not so powerful, but as the saying goes, “although a sparrow is small, it has all the five organs”. Shell also has some basic functions of high-level languages, such as functions and structured syntax like if… Else, while, etc

We’ve learned three installments of shell scripts:

  • Understand and learn the working mode and type of shell script in brief analysis of working principle of Shell script.

  • Introduction to Shell Script 1: Basic knowledge Learn the basic syntax of shell variables, arrays, and status codes

  • Introduction to Shell script 2: Functions are used to learn shell function definition, call, and parameter passing

In this installment, we will continue to learn more about the shell’s advanced syntactic structuring commands, Let’s go~

1. Overview of structured commands

Shell, as a programming language, also supports the use of structured commands

Structuring commands include: select structure, loop structure

  • Select structure: if.. then; . Fi and case in
  • Loop structures: for, while, until, SELECT
  • Others: break and continue

2. If-then

There are two main forms of if-then syntax:

  • The recommended format for an if statement
if [ condition ]
then
    cmds
elif [ condition ]
then
    cmds
else
    cmds
fi
Copy the code
  • You can also write “then” and “if” on one line
if [ condition ]; then
    cmds
elif [ condition ]
then
    cmds
else
    cmds
fi
Copy the code
  • Each side of square brackets has a space, must be added, otherwise an error;

  • You can compare values, strings, and files in square brackets

2.1 Numerical Comparison

To compare describe
n1 -eq n2 equal
n1 -ge n2 great or equal
n1 -gt n2 great than
n1 -le n2 less or equal
n1 -lt n2 less than
n1 -ne n2 not equal

2.2 String Comparison

To compare describe
str1 = str2 Str1 is equal to str2
str1 ! = str2 Str1 is not str2
str1 < str2 Str1 than str2
str1 > str2 Str1 than str2
-n str1 Is the length of str1 not zero
-z str1 Is the length of str1 0

< > < = > < = > < = > < = > < = > < = >

if [ $str1\ >$str2 ]
Copy the code

Is it a hassle?

Here we can use if-then’s advanced feature, double parentheses [[expression]]

Where are the higher brackets?

In addition to not needing to escape, you can also write matching patterns in parentheses, such as:

if [[ $USER == r*ky ]]
Copy the code

[[expression]

  • >, < do not need to escape, escape after error
  • There is no need to use “” for variable names, even if the variable is null, there is no error

PS: Forget single parentheses, use double parentheses!

2.3 File Comparison

File comparison in shell is used very much, very useful!!

To compare describe
-d file Check that file exists and is a directory
-e file Check whether file exists
-f file Check whether file exists and is a file
-r file Check that file exists and is readable
-w file Check that file exists and is writable
-x file Check that file exists and is executable
file1 -nt file2 equal
file1 -ot file2 equal

2.4 Compound Conditions

We can use && and | | multiple conditions are combined:

  • &&Is equivalent to and
  • ||Equivalent to ‘or’
if [ condition1 ] && [ condition2 ]
if [ condition1 ] || [ condition2 ]
Copy the code

3. Use of case

Case is also a branch of the shell structure, and is used when there are many criteria to judge.

Case grammar structure:

case variable in
pattern1 | pattern2) cmds1;;
pattern3) cmds2;;
*) default cmds;;
esac
Copy the code
  • Case, in, and esac are shell keywords
  • Variable is an expression, which can be a variable, a number, a string, a mathematical expression, or a command execution result
  • Pattern is a matching pattern, which can be a number, a string, or a regular expression

4. Use of the for loop

The shell loop for, like any other language, is flexible to use and simple to code

For loop syntax structure:

The standard structure is as follows

for((exp1; exp2; exp3))do
	cmds
done
Copy the code
  • Exp1, exp2, exp3 are three expressions, exp1 is an initialization statement, exp2 is a judgment condition, exp3 is autoincrement or autodecrement, can be omitted
  • CMDS is a loop body syntax, which can have one or more loops
  • Do and done are key players in the shell

The shell for loop also supports Python’s for notation

for var in list
do
	cmds
done
Copy the code

List Format description

  1. The value of the specific

    The in keyword can be followed by specific values, separated by Spaces, such as 10, 20, 30, “hello”, “jue”, “jin”

for var in10 to 20 30do
       echo $var
done
Copy the code
  1. Value range

    • You can use {start.. end}

    • Start indicates the start value and end indicates the end value

    • Connect them with two dots

for var in{A.. z}do
       echo $var
done
Copy the code
  1. The command is executed

Use either backquotes or $() to get the result of the command

sum=0

for var in $(seq 2 2 100)
do
    ((sum+=n))
done

echo $sum
Copy the code
  1. Use shell wildcards

Shell wildcards are considered a simplified form of regular expression

Usually used to match directories or files, not text

for file in *.txt
do
    echo $file
done
Copy the code
  1. Special variables

We learned about some special variables in the function:

$# : indicates the number of input arguments. $* : treats all command line arguments as a whole. $@ : Gets the array of parameters passed inforLoop through $? : Gets the status code or function return value. $$: indicates the ID of the current shell processCopy the code
function func() {for str in $@
    do
        echo $str
    done
}

func hello jue jin
Copy the code

5. Use of while

The while loop is the simplest type of loop for shell scripts.

The syntax format of while is:

while conditions
do
    cmds
done
Copy the code
  • Condition: indicates the judgment condition
  • CMDS: Represents the statement to be executed

The execution flow of the while loop is:

  • Condition is evaluated first. If true, enter the loop and execute do… Done the loop body
  • Once done is executed, condition is evaluated again, and if true, the loop body is continued
  • If it is not supported, the while loop is exited

Let’s look at an example 🌰 :

var1=10
while [ $var1 -gt 0 ]
do
    echo $var1
    var1=$[ $var11]done
Copy the code

6

The until loop execution logic is the opposite of the while loop, in that the loop is executed when the judgment condition is not standing and terminates once the judgment is successful

Until now

until conditions
do
    cmds
done
Copy the code
  • Condition: indicates the judgment condition
  • CMDS: statements executed

i=1
sum=0

until ((i > 100))
do

    ((sum +=i))
    ((i++))
done
echo $sum

Copy the code

Compared with the while loop, the judgment condition is ((I <=100)).

7. Break command

When using a loop, you can use break to break out of the loop body when the condition is met

The break keyword is usually used with the if statement to break out of the loop when the condition is met.

Let’s look at the following case:

When var is equal to 5, the while loop follows

while [ $var1 -lt 10 ] 
do 
    if [ $var1 -eq 5 ] 
    then 
        break 
    fi 
        echo "Iteration: $var1" 
        var1=$[ $var1+ 1]done
Copy the code

8. The continue command

The continue keyword indicates that if conditions are met, the next step will be skipped and the next loop will continue

The continue keyword is also commonly used with if statements

Let’s look at a case as follows:

When var is equal to 5, the print is skipped and subsequent numbers are printed

for var1 in1, 2, 3, 4, 5, 6, 7, 8, 9, 10do 
    if [ $var1 -eq 5 ] 
    then 
        continue 
    fi 
        echo "Iteration number: $var1" 
done 
Copy the code

9. Use the command line toolset

The shell itself is also a command interpreter, with many useful tools as follows:

$ tr			# transformation
$ sed
$ awk
$ cut
$ find 
$ grep
$ du			# disk usage
$ df			# disk free
$ ps
$ top
$ kill
$ killall
Copy the code

conclusion

In this installment, learn how to use structured commands for the introduction to shell syntax.

  • Select structure syntax has if… then; . Fi, case structure
  • Logical structure syntax has for, while, until structures

So far, we have almost learned the basic shell syntax. In our daily work, shell scripts help us achieve partial automation

This is the content of this issue, welcome you to like the comments, ♥️ ~