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

preface:

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
commands
...

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 first_shell.sh
#!/bin/env bash

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

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

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

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

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 first_shell.sh
[root@MissHou shell01]# sh first_shell.sh
[root@MissHou shell01]# bash -x first_shell.sh
+ 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 first_shell.sh
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 "$"
hello
[root@MissHou ~]# echo ${A} 		 You can also call it like this. No matter how elegant your posture is, you have to pay
hello
[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
world
[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
hello
[root@MissHou ~]# echo $a
world

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
123

Try to know the meaning of five variable names

NTP_IP=10.1.1.1
DIR=/u01/app1
TMP_FILE=/var/log/1.log
...

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
1234567
[root@MissHou ~]# echo ${A:2:4} 		 It means to intercept from the third character in a variable and intercept 4 characters
3456

explain:
$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
2019-04-16
[root@MissHou ~]# C=$(uname -r)
[root@MissHou ~]# echo $C
2.6.32-696.el6.x86_64

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:

optioninterpretation
-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
harry
[root@MissHou ~]# echo $name
harry
[root@MissHou ~]# read -p "Input your name:" name
Input your name:tom
[root@MissHou ~]# echo $name
tom

Usage 2: variable value from file

[root@MissHou ~]# cat 1.txt 
10.1.1.1 255.255.255.0

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

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
123
[root@MissHou ~]# A=hello
[root@MissHou ~]# echo $A
0

[root@MissHou ~]# declare -r B=hello
[root@MissHou ~]# echo $B
hello
[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
A=hello

Permanently effective:
vim /etc/profile perhaps ~/.bashrc
export A=hello
 perhaps
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}
#!/bin/bash
#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

#!/bin/bash
for i in "$@"
do
echo $i
done

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

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

[root@MissHou ~]# bash 3.sh a b c
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
2
[root@MissHou ~]# j=1
[root@MissHou ~]# let ++j
[root@MissHou ~]# echo $j
2
  • 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
2
[root@MissHou ~]# echo $j
2
[root@MissHou ~]# echo $x
1
[root@MissHou ~]# echo $y
2

Topics: Linux bash