The article directories

  • I. About shell
    • 1. What is shell
    • 2. Introduction to shell
  • Ii. Advanced Shell (key points)
    • 1. Variables (key points)
      • 1.1. Meanings of variables
      • 1.2 Definition and Use of variables (emphasis)
      • 1.3. Read-only variables (Understand)
      • 1.4 Receiving user input (key)
      • 1.5. Delete variables (Understanding)
    • 2. Conditional statement
    • 3. Operators
      • 3.1 Arithmetic operators
      • 3.2. Relational operators
      • 3.3. Logical operators
      • 3.4. String operators
      • 3.5. File test operators (emphasis)
    • 4. Optional shell scripts (key)

I. About shell

1. What is shell

What is a shell?

  • Shell(Shell) is a useCProgramming language, it is the user using Linux bridge.ShellIt is both a command language and a programming language.
  • ShellAn application that provides an interface through which users access operating system kernel services.

What is a script?

  • A script is simply a series of text commands that can be seen (for example, open to view and edit with Notepad).
  • Common scripts:JavaScript (JS, front-end), VBScript, ASP, JSP, PHP (back-end), SQL (database operation language), Perl, Shell, Python, Ruby, JavaFX, LuaAnd so on.

Why learn and use the shell?

  • The Shell is a built-in script
  • Program development is very efficient, relying on powerful commands to complete development tasks quickly (batch processing)
  • The syntax is simple, the code is easy to write, simple and easy to learn

Common shell types?

  • There are many types of shells in Linux, and different shells have different functions. Shells also determine the syntax of functions in scripts. The default shell in Linux is /bin/bashAsh, bash, KSH, CSH, ZSHAnd so on. Different shells have their own characteristics and uses.
  • CSH C shell uses “C-like” syntax. CSH is a shell with the style of C language and has 52 internal commands, which are relatively large. Not much is currently in use and has been replaced by /bin/tcsh.
  • The syntax of KSH Korn shell is the same as Bourne shell, and it is easy to use like C Shell. Many installation scripts use KSH, which has 42 internal commands and is somewhat more restrictive than bash.
  • TCSH TCSH is an enhanced version of CSH and fully compatible with C Shell.
  • Sh is a shortcut that has been replaced by /bin/bash.
  • nologin

    Indicates that the user cannot log in

  • ZSH The biggest shell in Linux: ZSH. It has 84 internal commands and is complicated to use. In general, this shell is not used.
  • Bash Bash is the default shell used by most Linux systems. Bash shell is a free version of the Bourne shell, which is the earliest Unix shell. Bash also features the help command to view help. Contains almost everything the shell does, so a typical shell script will specify it as the execution path.

2. Introduction to shell

  • Write specifications:
  • Code specification:
#! /bin/bash [specifies the shell interpreter to tell the system to use for the current script] shell-related instructionsCopy the code
  • File naming conventions:
Sh is the default suffix of bash shell in LinuxCopy the code
  • Use process:

    ① Create the. Sh filetouch/vim

    ② Write shell code

    ③ Executing shell scripts Scripts must have execution permission
  • Case 1: Createtest.shTo implement the first shell script, outputhello world.

    Output command:# echo 123
  • Note: If the output contains letters and symbols (not variables), it needs to be enclosed in quotes. If it is a pure number, it may or may not be included.



  • Pay attention to: this must be written at runtime./test.shRather thantest.shRun other binary programs as well, write directlytest.shLinux will goPATH(Environment variables) look for callstest.shBut only/bin./sbin./usr/bin./usr/sbinSuch as inPATHIn, your current directory is usually not therePATHIn, so it’s written astest.shYou won’t find the order. Use it./test.shTell the system to look in the current directory.
  • Case 2: UserootThe user account is created and executedtest2.shImplementation creates oneshelltestUser and create a new file in their home directorytry.html.

  • Another way to execute a script:/bin/bash Specifies the path of the bash script(understand)

  • Shell scripts are divided into simple (stacking of simple commands) and complex (programming)

Ii. Advanced Shell (key points)

1. Variables (key points)

1.1. Meanings of variables

  • A. What is quantity? Quantity is data.
  • B. What is a variable data can change is a variable. A variable is how much its value can change over the course of a script cycle.
  • C. What is a script cycle

    A script cycle can simply be understood as the current oneshellfile
  • A variable isshellIs an indispensable part of, is also the most basic, the most important component.

1.2 Definition and Use of variables (emphasis)

  • Variable, defined before use.
  • The definition looks like:class_name="yunwe "
  • Such as:echo $class_name
  • A variable consists of two parts: the name of the variable (left) and the value of the variable (right)
  • What is the relationship between a variable name and its value? Variable names and variable values are used and used relationships; Our variable name uses the variable value;
  • When using a variable, always add one in front of the variable name$Symbol, a requirement that exists in other languages (such as PHP).

Note that there can be no Spaces left or right after an equal sign, unlike in any programming language you’re familiar with. In addition, the naming of variable names must follow the following rules:

  • The name must contain only letters, digits, and underscores (_). The first character cannot start with a number.
  • There can be no Spaces between them. Instead, use the underscore “_”.
  • Do not use punctuation marks.
  • You can’t usebashThe key words in thehelpCommand to view reserved keywords.

Case 1: Rewrite the first shell script in the getting started script using variables.





Question about single and double quotation marks:

  • Double quotes recognize variables, and double quotes can be escaped (similar to”\“).
  • Single quotes do not recognize variables and only output as is. Single quotes cannot be escaped

Case 2: Define a variable and output the current time in the format of “year-month-day hour: minute: second”.

  • Note: The backquotes (escThe key below the key) is used when executing instructions in a script and assigning the result to a variable.The quotation marks“.

1.3. Read-only variables (Understand)

  • Grammar:Readonly variable name
  • Example: Define variable A with a value of 10, then make it read-only, and try to reassign



1.4 Receiving user input (key)

  • Grammar:Read-p Indicates the variable name of the prompt
  • Example: Write a scripttest6.shTo prompt the user to enter the name of the file (path) after execution, and then automatically create the file for the user



1.5. Delete variables (Understanding)

  • Grammar:Unset the variable name
  • Example: Define variablesb=20, then print the value of b, then delete b, and finally print b



2. Conditional statement

  • Syntax 1 (one condition) :
if condition
then
    command1 
    command2
    ...
fi
Copy the code
  • Single-line (usually executed on the command line) :if [ condition ]; then command; fi
  • Syntax 2 (two conditions) :
if condition
then
    command1 
    command2
    ...
else
    command
fi
Copy the code
  • Syntax 3 (multiple conditions) :
if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi
Copy the code

3. Operators

  • Operators in shell, like other programming languages, are common arithmetic operators, relational operators, logical operators, string operators, file test operators, etc

3.1 Arithmetic operators

  • The following table lists the commonly used arithmetic operators, assuming variable A is 10 and variable B is 20:

  • Note: Conditional expressions should be placed between square brackets with Spaces, for example:[$a==$b]Is wrong, must be written

    [ $a == $b ].
  • nativebashSimple math is not supported, but can be done with other commands, such asawkExpr, expr

    The most commonly used.
  • exprIs an expression calculation tool, using it to complete the expression of the evaluation operation.
  • For example, add two numbers (note the use of back quotes) :
#! /bin/bash
val=`expr 2 + 2`
echo "The sum of the two numbers is:$val"
Copy the code

Two points to note:

  • There must be a link between an expression and an operatorThe blank space, e.g.2 + 2That’s not true. It has to be written2 + 2Unlike most programming languages we are familiar with.
  • The full expression is to beThe quotation marksContains, note that this character is not the usual single quotation mark, inEscButton below.



3.2. Relational operators

  • Relational operators only support numbers, not strings, unless the value of the string is a number.
  • The following table lists the commonly used relational operators, assuming variable A is 10 and variable B is 20:

-eq: equal -ne: not equal -gt: great than -lt: less than -ge: great than or equal -le: less than or equalCopy the code
  • Example: Use a=10, b=20 to implement this example



  • Practice:

    Write a script to determine whether the currently entered user exists. If yes, the system displays User Exists; otherwise, the system displays User does not exist.

3.3. Logical operators

  • The following table lists the common Boolean operators, assuming that variable A is 10 and variable B is 20:

  • Or operation: if one is true, it is true; if all are false, it is false
  • And operation: if one is false, it is false; if all are true, it is true

3.4. String operators

  • The following table lists the common string operators, assuming variable A is “ABC” and variable B is “efg” :



  • Example: Verify the above syntax

3.5. File test operators (emphasis)

  • File test operators are used to detect various properties of Unix/Linux files.
  • Attribute detection is described as follows:



  • Case study: Test the effect of the above color green

  • Note: Permission several judgments, if only one part of the match, it is considered to have permission.

4. Optional shell scripts (key)

  • How to handle command line options like tail-10 access.log in Linux shell?
  • Steps:
The tail instruction system is called to pass the subsequent options to tail, which first opens the specified file and fetches the last 10 linesCopy the code
  • Question: I wrote it myselfshellIs it possible to pass options as well as built-in commands?
  • Answer: yes, the transfer mode is the same as the above description, the key is how to receive. Such as:
  • Delivery:
#./test.sh  a  b  c
Copy the code
  • Receive: In a script you can use “$1” for A, “$2” for B, and so on.
  • The receiver can use “$” and the corresponding serial number of the option.

Testing: writingtest14.sh, pass a, b, c, and print its value



$1, $2 are variables.

Exercise: Create a custom directive “user” that can be executed directly, requiring the command to have the following syntax and functions:

A. # user-add user name 【 add user 】 b. # user-del user name 【 delete user and home directory 】Copy the code



Add individual names: