Chapter three is about the definition of variables in Shell topics & four operations

Posted by elie on Fri, 11 Feb 2022 08:01:16 +0100

1, SHELL introduction


Computers can only recognize (recognize) machine languages (0 and 1), such as (11 million). However, our program apes can't write code like 01 directly. Therefore, if we want to run the code developed by program apes on the computer, we must find a "person" (tool) to translate it into machine language. This "person" (tool) is what we often call * * compiler or interpreter * *.

1. Classification of programming languages

  • Compiled language:

Before the program is executed, a special compilation process is required to compile the program into a machine language file. There is no need to re translate it at runtime, and the compiled results can be used directly. The program has high execution efficiency, depends on the compiler, and has poor cross platform performance. Such as C, C++

  • Interpretive language:

The program does not need to be compiled. When the program is running, it is translated into machine language by * * interpreter * *, and it must be translated every time it is executed. Therefore, the efficiency is relatively low. For example, Python/JavaScript/ Perl /ruby/Shell are interpreted languages.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1gtua08a-1644203746857) (language classification. png)]

  • summary

Compiled languages are faster than interpreted languages, but they are not as cross platform as interpreted languages. If you do low-level development or large-scale application or operating system development, you generally use compiled language; If some server scripts and some auxiliary interfaces have low requirements for speed and compatibility of various platforms, interpretive languages are generally used.

2. shell introduction

  • shell is a bridge of human-computer interaction
  • Type of shell
[root@MissHou ~]# cat /etc/shells 
/bin/sh				#Is a shortcut to bash
/bin/bash			#bash is the default shell of most Linux. It contains almost all functions of the shell
/sbin/nologin		#It means non interactive and cannot log in to the operating system
/bin/dash			#Small, efficient and less functional

/bin/csh				#A shell with C language style, which has many features, but also has some defects
/bin/tcsh			#It is an enhanced version of csh and is fully compatible with csh

3. shell script

What is a shell script?

  • One sentence summary

Simply put, it is to save the commands to be executed into the text and execute them in order. It doesn't need to be interpreted.

  • Accurate narration

Several commands + basic format of script + specific syntax of script + thought = shell script

When will the script be used?

Repetitive and complicated work, which can be completed by writing the work command into a script and only executing the script in the future.

What can three shell scripts do?

① Automated software deployment LAMP/LNMP/Tomcat

② Automatic management system initialization script, batch change of host password, push public key

③ Automatic analysis and processing, statistics of website visits

④ Automatic backup, database backup, log dump

⑤ Automated monitoring script

How to learn shell script?

  1. Memorize as many commands as possible (memorize command functions and scenes)
  2. Master the standard format of the script (specify magic bytes and run the script in standard execution mode)
  3. Must be familiar with the basic syntax of = = Script (key points)

Five tips for learning shell scripts

Read more (understand) - > imitate (practice more) - > think more (write more)

Vi. basic writing method of shell script

1) The first line of the script, magic character = = #== Specify interpreter [required]

#!/ bin/bash means that the following is parsed using bash interpreter

be careful:
If the interpreter path is directly written in the script, there may be a compatibility problem that the interpreter cannot be found in some systems, so you can use: #/ Bin / env interpreter #/ bin/env bash

2) The second part of the script, notes (# No.) description, describes the basic information of the script [optional]

#!/bin/env bash

# The following is a description of the basic information of the script
# Name: name
# Desc: describe
# Path: storage path
# Usage: Usage
# Update: update time

#The following is the specific content of the script

3) The third part of the script is the specific code content to be realized by the script

VII. Execution method of shell script

  • Standard script execution method (recommended)
1) Write the first in life shell script
[root@MissHou shell01]# cat
#!/bin/env bash

# The following is a description of the basic information of the script
# Name:
# Desc: num1
# Path: /shell01/
# Usage:/shell01/
# Update:2019-05-05

echo "hello world"
echo "hello world"
echo "hello world"

2) Add executable permissions to scripts
[root@MissHou shell01]# chmod +x

3) Execute scripts in a standard way
[root@MissHou shell01]# pwd
[root@MissHou shell01]# /shell01/
[root@MissHou shell01]# ./

Note: the standard execution mode script must have executable permission.
  • Non standard implementation method (not recommended)
  1. Specify the interpreter to execute directly on the command line
[root@MissHou shell01]# bash
[root@MissHou shell01]# sh
[root@MissHou shell01]# bash -x
+ echo 'hello world'
hello world
+ echo 'hello world'
hello world
+ echo 'hello world'
hello world
-x:It is generally used to troubleshoot and view the execution process of the script
-n:Used to check whether there is a problem with the syntax of the script
  1. Use the source command to read the script file and execute the code in the file
[root@MissHou shell01]# source
hello world
hello world
hello world

**Small test ox knife: * * write a script with wood and soul. The requirements are as follows:

  1. Delete all files in the / tmp / directory

  2. Then create three directories in the / tmp directory, dir1~dir3

  3. Copy the / etc/hosts file to the newly created dir1 directory

  4. Finally, print the content of "report chief, the task has been completed at 10:10:10 on May 5, 2019"

    echo "report to the head that the task has been completed on $(date + '% F% t')"

2, Defined variable

1. What are the variables?

In one sentence: variables are used to temporarily save data, which can be changed.

2. When do I need to define variables?

  • If a content needs to be used multiple times and appears repeatedly in the code, the content can be represented by variables. In this way, when modifying the content, you only need to modify the value of the variable.
  • In the process of code operation, the execution results of some commands may be saved. If subsequent codes need to use these results, they can directly use this variable.

3. How to define variables?

*Variable name = = = = = variable value*

Variable name: used to temporarily save data

Variable value: temporary variable data

[root@MissHou ~]# A=hello 			 Define variable a
[root@MissHou ~]# echo $A 			 Call variable a to give money, not RMB, but USD "$"
[root@MissHou ~]# echo ${A} 		 You can also call it like this. No matter how elegant your posture is, you have to pay
[root@MissHou ~]# A=world 			 Because it is a variable, it can be changed. Empathy is common
[root@MissHou ~]# echo $A 			 No matter who you are, you have to pay as long as you call
[root@MissHou ~]# unset A 			 Stop playing with you and cancel the variable
[root@MissHou ~]# echo $A 			 Since then, I am single. You can introduce anyone to me

4. Definition rules of variables

Although you can assign any value to the variable (variable name); However, variable names are also required! 😒

A variable name is case sensitive

[root@MissHou ~]# A=hello
[root@MissHou ~]# a=world
[root@MissHou ~]# echo $A
[root@MissHou ~]# echo $a

Binary variable names cannot have special symbols

[root@MissHou ~]# *A=hello
-bash: *A=hello: command not found
[root@MissHou ~]# ?A=hello
-bash: ?A=hello: command not found
[root@MissHou ~]# @A=hello
-bash: @A=hello: command not found

Special note: for strings with spaces, when assigning values to variables, they should be enclosed in quotation marks
[root@MissHou ~]# A=hello world
-bash: world: command not found
[root@MissHou ~]# A="hello world"
[root@MissHou ~]# A='hello world'

Three variable names cannot begin with a number

[root@MissHou ~]# 1A=hello
-bash: 1A=hello: command not found
[root@MissHou ~]# A1=hello
 Note: not starting with a number does not mean that the variable name cannot contain a number.

There must be no spaces on either side of the equal sign

[root@MissHou ~]# A =123
-bash: A: command not found
[root@MissHou ~]# A= 123
-bash: 123: command not found
[root@MissHou ~]# A = 123
-bash: A: command not found
[root@MissHou ~]# A=123
[root@MissHou ~]# echo $A

Try to know the meaning of five variable names


Note: generally, variable names are in uppercase (lowercase is also acceptable). Do not use all variables in the same script a,b,c Waiting is not easy to read

5. What are the definition methods of variables?

I. Basic Mode

Assign directly to a variable

[root@MissHou ~]# A=1234567
[root@MissHou ~]# echo $A
[root@MissHou ~]# echo ${A:2:4} 		 It means to intercept from the third character in a variable and intercept 4 characters

$Variable name and ${Variable name}Similarities and differences
 Same point: all variables can be called
 difference: ${Variable name}You can intercept only part of the variable, and $Variable name is not allowed

Second, assign the command execution result to the variable

[root@MissHou ~]# B=`date +%F`
[root@MissHou ~]# echo $B
[root@MissHou ~]# C=$(uname -r)
[root@MissHou ~]# echo $C

Three interactive definition variables (read)

**Purpose: * * allow users to assign values to variables themselves, which is more flexible.

Syntax: read [options] variable name

Common options:

-pDefines the information that prompts the user
-nDefine the number of characters (limit the length of variable values)
-sDo not display (do not display user input)
-tDefine the timeout time, and the default unit is seconds (limit the timeout time of user input variable value)

For example:

Usage 1: user defined variable value
[root@MissHou ~]# read name
[root@MissHou ~]# echo $name
[root@MissHou ~]# read -p "Input your name:" name
Input your name:tom
[root@MissHou ~]# echo $name

Usage 2: variable value from file

[root@MissHou ~]# cat 1.txt

[root@MissHou ~]# read ip mask < 1.txt 
[root@MissHou ~]# echo $ip
[root@MissHou ~]# echo $mask

Four defined variables

Purpose: make some restrictions on variables and fix the types of variables, such as integer and read-only

Usage: declare option variable name = variable value

Common options:

optioninterpretationgive an example
-iTreat variables as integersdeclare -i A=123
-rDefine read-only variablesdeclare -r B=hello
-aDefine ordinary array; View normal array
-ADefine associative arrays; View associative arrays
-xExport variables through environmentdeclare -x AAA=123456 equals export AAA=123456

For example:

[root@MissHou ~]# declare -i A=123
[root@MissHou ~]# echo $A
[root@MissHou ~]# A=hello
[root@MissHou ~]# echo $A

[root@MissHou ~]# declare -r B=hello
[root@MissHou ~]# echo $B
[root@MissHou ~]# B=world
-bash: B: readonly variable
[root@MissHou ~]# unset B
-bash: unset: B: cannot unset: readonly variable

6. Classification of variables

A local variable

  • Local variable: a variable defined by the current user. Valid in the current process, other processes and child processes of the current process are invalid.

II. Environmental variables

  • Environment variable: the current process is valid and can be called by child processes.
    • env view the environment variables of the current user
    • set queries all variables (temporary variables and environment variables) of the current user
    • export variable name = variable value or variable name = variable value; export variable name
[root@MissHou ~]# export A=hello 		 Temporarily change a local variable (temporary variable) into an environment variable
[root@MissHou ~]# env|grep ^A

Permanently effective:
vim /etc/profile perhaps ~/.bashrc
export A=hello
export A

Description: there is a variable in the system PATH,environment variable
export PATH=/usr/local/mysql/bin:$PATH

Three global variables

  • Global variable: all users and programs in the world can call and inherit, and new users can call by default

  • Interpretation of relevant configuration files

file nameexplainremarks
$HOME/.bashrcbash information of the current user, which is read when the user logs inDefine aliases, umask, functions, etc
$HOME/.bash_profileThe environment variable of the current user, which is read when the user logs in
$HOME/.bash_logoutLast read when the current user exits the current shellDefine the program executed when the user exits, etc
/etc/bashrcThe global bash information is valid for all users
/etc/profileGlobal environment variable informationThe system and all users are effective
$HOME/.bash_historyUser's historical commandshistory -w save history -c clear history

**Note: * * after the above files are modified, you need to re source to make them effective or log out and log in again.

  • The order in which users log in to the system to read relevant files
    1. /etc/profile
    2. $HOME/.bash_profile
    3. $HOME/.bashrc
    4. /etc/bashrc
    5. $HOME/.bash_logout

Four system variables

  • System variable (built-in variable in bash): the shell itself has fixed its name and function
Built in variablemeaning
$?The status returned after the execution of the previous command; A status value of 0 indicates normal execution, and a non-0 indicates abnormal execution or error
$0Name of the program or script currently executing
$#The number of parameters followed by the script
$*All parameters behind the script are output as a whole, and each variable parameter is separated by a space
$@All parameters behind the script are independent and output
$1~$9For the location parameter after the script, $1 represents the first location parameter, and so on
${10}~${n}To expand the location parameter, the 10th location variable must be enclosed in {} braces (expanded with more than 2 digits)
$$The process number of the current process, such as echo$$
$!The last process number running in the background (current terminal)
!$Call the parameters in the last command history
  • Learn more about the location parameter $1~${n}
#Understand the meaning of location parameters in shell built-in variables
echo "\$0 = $0"
echo "\$# = $#"
echo "\$* = $*"
echo "\$@ = $@"
echo "\$1 = $1" 
echo "\$2 = $2" 
echo "\$3 = $3" 
echo "\$11 = ${11}" 
echo "\$12 = ${12}" 
  • Learn more about the difference between $* and $@

$*: indicates that the variable is regarded as a whole
$@: indicates that the variable is independent

for i in "$@"
echo $i

echo "======I am the dividing line======="

for i in "$*"
echo $i

[root@MissHou ~]# bash a b c
======I am the dividing line=======
a b c

3, Simple four arithmetic

Arithmetic operation: by default, the shell can only support simple integer operation

Operation contents: addition (+), subtraction (-), multiplication (*), division (/), remainder (%)

1. Four arithmetic symbols

expressiongive an example
$(( ))echo $((1+1))
$[ ]echo $[10-5]
exprexpr 10 / 5
letn=1;let n+=1 is equivalent to let n=n+1

2. Understand i + + and + + i

  • Influence on the value of variable
[root@MissHou ~]# i=1
[root@MissHou ~]# let i++
[root@MissHou ~]# echo $i
[root@MissHou ~]# j=1
[root@MissHou ~]# let ++j
[root@MissHou ~]# echo $j
  • Effect on the value of the expression
[root@MissHou ~]# unset i j
[root@MissHou ~]# i=1;j=1
[root@MissHou ~]# let x=i + + assign values first and then operate
[root@MissHou ~]# Let y = + J operate first and then assign value
[root@MissHou ~]# echo $i
[root@MissHou ~]# echo $j
[root@MissHou ~]# echo $x
[root@MissHou ~]# echo $y

Topics: Linux bash