shell script learning

Posted by dnienhaus on Tue, 28 Sep 2021 23:20:39 +0200

shell script

1, What is a shell

Shell is a program written in C language. It is a bridge between users and linux kernel. It is not only a command language, but also an interpretative programming language. Use a chart to see what the shell does

**Expand knowledge:**
**kernel: Serve the software, receive user or software instructions, drive the hardware and complete the work;**
**shell: command interpreter**
**user: User interface, docking users.**

As can be seen from the figure above, the shell plays the role of accepting users and system kernel in the operating system. So why not direct users to the kernel? The reason is very simple, because the kernel deals with binary, while the user deals with high-level languages.

2, shell syntax

1. How to write a shell script

Naming of shell script:
The name should be meaningful. It's best not to name it in the way of a, b, c, d, 1, 2, 3 and 4; Although there is no concept of file extension in linux system, it is still recommended that you end with. sh.
shell script format:
At the beginning of shell script, you must specify the script running environment to #! This special symbol combination. For example: #/ bin/bash specifies that the script is run and parsed by / bin/bash (you can also write #! / usr/bin/env bash/python), and the # number is used for comments in the shell

#In the shell script, it is better to add the script description field
#!/bin/bash
#Author: Bai Shuming
#Created Time: 2018/08/2712:27
#Script Description: first shell study script

2. Run a shell script

The script needs execution permission to run. When we give execution permission to a file, the script can run.
#chmod u+x filename
 If you do not want to grant script execution permission, you can use bash Command to run a script that is not given execution permission bash fiename
#bash filename

3. Special symbols in shell

Basic students should not be confused with the symbolic meaning in regular expressions.
~:                Home directory    # cd ~ represents entering the user's home directory
!:                Execute history command   !! Execute the previous command
$:                Get content character from variable
+ - * \ %:       Addition, subtraction, multiplication, division and remainder of corresponding mathematical operation  
&:                Background execution
*:                The asterisk is shell Wildcards in match all
?:                The question mark is shell The wildcard in matches a character other than carriage return
;:                Semicolons can be shell Multiple commands are executed on one line, separated by semicolons
|:                The output of the previous command is used as the input of the next command   cat filename | grep "abc"
\:                Escape character
``:               Execute command in backquote command    echo "today is `date +%F`"
' ':              Single quotation marks. Strings in scripts should be enclosed in single quotation marks, but unlike double quotation marks, single quotation marks do not interpret variables
" ":              Double quotation marks. Strings appearing in the script can be enclosed in double quotation marks

Some examples:

4. Pipeline application in shell

|  Pipe symbol in shell It is most used in. Many combined commands need to complete the output through combined commands. The pipe symbol is actually the next command processing the output of the previous command.

5.shell redirection

>   Redirect input overwrite original data
>>  Redirect additional input and add at the end of the original data
<   redirect output     wc -l < /etc/passwd
<<  Redirect additional output  fdisk /dev/sdb <

>And > >

< examples of

Note: EOF can use END instead of parentheses, and n and p need to be written in the top grid

6. Mathematical operation

 expr Command: only integer operations can be performed. The format is rather old-fashioned. Pay attention to spaces
 [root@baism ~]# expr 1 + 1
 2
 [root@baism ~]# expr 5 - 2
 3
 [root@baism ~]# expr 5 \* 2  #Note that * should be escaped, otherwise it is considered as a wildcard
 10
 [root@baism ~]# expr 5 / 2
 2
 [root@baism ~]# expr 5 % 2
 1
 
 use bc The calculator handles floating-point operations,scale=2 Two decimal places are reserved
 [root@baism ~]# echo "scale=2;3+100"|bc
 103
 [root@baism ~]# echo "scale=2;100-3"|bc
 97
 [root@baism ~]# echo "scale=2;100/3"|bc
 33.33
 [root@baism ~]# echo "scale=2;100*3"|bc
 300
 [root@baism ~]# echo "`echo "scale=2;141*100/7966"|bc`%"
 1.77%
 
 Double parenthesis operation, in shell in(( ))It can also be used to do mathematical operations
 [root@baism ~]# echo $(( 100+3))
 103
 [root@baism ~]# echo $(( 100-3)) 
 97
 [root@baism ~]# echo $(( 100%3))
 1
 [root@baism ~]# echo $(( 100*3))
 300
 [root@baism ~]# echo $(( 100/3))
 33
 [root@baism ~]# echo $(( 100**3))     #Square operation
 1000000

Note: $? A return of 0 indicates that the previous instruction was executed successfully. A non-0 indicates that the previous instruction was not executed successfully. Examples are as follows:

7. Exit script

exit NUM Exit the script and release system resources, NUM Represents an integer and represents the return value. NUM=[1,255]

3, shell formatted output

1. Introduction to echo command

The function of echo command is to display a text on the display, which generally plays the role of a prompt. The general format of this command is: echo [- n] string, where option n means no line break after outputting text; Strings can be quoted or not.
When outputting a quoted string with echo command, output the string as it is; When outputting an unquoted string with echo command, each word in the string is output as a string, and each string is separated by a space.

echo [-ne][character string]or echo [—help][—version]
Supplementary notes:echo The input string is sent to standard output. The output strings are separated by white space characters,And add the line number at the end.

Command options:
-n Don't wrap at the end
-e If the following characters appear in the string, they will be specially processed instead of being output as general text:

Escape character
\a Sound a warning tone;
\b To delete the previous character, it must be on the same line;
\c No line breaks at the end;
\f Line breaks, but the cursor remains in its original position;
\n Wrap a line and move the cursor to the beginning of the line;
\r Move the cursor to the beginning of the line without wrapping;
\t insert tab;
\v And\f identical;
\insert\character;
\nnn insert nnn(octal number system)Represented by ASCII character;
–help Show help–version display version information

Examples are as follows

2. Color code

The echo display content in the script is displayed in color, and the echo display is displayed in color. The parameter - e is required
The format is as follows:
echo -e "\ 033 [word background color; text color M string \ 033[0m"
For example:
echo -e "\033[41;36m something here \033[0m"
The position of 41 represents the background color and the position of 36 represents the color of the word
1. Between the background color and the text color is English "
2. There is an m after the text color
3. There can be no spaces before and after the string. If any, the output also has spaces

The following are the corresponding words and background colors. You can try to find out different color combinations by yourself
 example
echo -e "\033[31m Red characters \033[0m"
echo -e "\033[34m Yellow word \033[0m"
echo -e "\033[41;33m Yellow characters on red background \033[0m"
echo -e "\033[41;37m White characters on red background \033[0m"
  
Font color: 30 -–37
echo -e "\033[30m Black characters \033[0m"
echo -e "\033[31m Red characters \033[0m"
echo -e "\033[32m Green word \033[0m"
echo -e "\033[33m Yellow word \033[0m"
echo -e "\033[34m Blue word \033[0m"
echo -e "\033[35m Purple character \033[0m"
echo -e "\033[36m Sky blue character \033[0m"
echo -e "\033[37m White words \033[0m"
  
Word background color range: 40 -–47
echo -e "\033[40;37m White characters on black background \033[0m"
echo -e "\033[41;37m White characters on red background \033[0m"
echo -e "\033[42;37m White characters on green background \033[0m"
echo -e "\033[43;37m White characters on yellow background \033[0m"
echo -e "\033[44;37m White characters on blue background \033[0m"
echo -e "\033[45;37m White characters on purple background \033[0m"
echo -e "\033[46;37m White characters on sky blue background \033[0m"
echo -e "\033[47;30m Black characters on white background \033[0m"
  
Last control option description
\033[0m Close all properties
\033[1m Set high brightness
\033[4m Underline
\033[5m twinkle
\033[7m Reverse display
\033[8m Blanking
\033[30m — \33[37m 
set foreground color 
\033[40m — \33[47m Set background color
\033[nA Move cursor up n that 's ok
\033[nB Cursor down n that 's ok
\033[nC Move cursor right n that 's ok
\033[nD Move cursor left n that 's ok
\033[y;xH Set cursor position
\033[2J Clear screen
\033[K Clears the contents from the cursor to the end of the line
\33[s Save cursor position
\033[u restore cursor position 
\033[?25l hide cursor
\033[?25h Display cursor

4, shell basic input

1.read command

Keyboard input is accepted by default, and the carriage return indicates the end of input
read Command options
-p Print information
-t Limited time     for example-t5 It means that it must be entered within 5 seconds, otherwise it will exit directly
-s Do not echo       It is generally used for password input
-n Enter the number of characters, for example-n10 Indicates that the maximum number of characters entered is 10, and more than 10 characters will stop automatically

Examples are as follows:

5, shell variable

1. Define variables

Variable format: variable name = value
In shell programming, there cannot be spaces between variable names and equal signs.

Variable name naming rules:
Naming can only use English letters, numbers and underscores. The first character cannot start with a number.
There can be no spaces in the middle. You can use underscores(_). 
Punctuation cannot be used.
out of commission bash Keywords in (available) help Command (view reserved keywords).
VAR1=1
age=18
name='baism'
score=88.8
 Note: the string should be enclosed in single quotation marks or double quotation marks
 Demonstration of defining variables:
Variable assignment, this method is set as a local variable
[root@www ~]# name="baism"
[root@www ~]# school='ayitula'
[root@www ~]# age=30
[root@www ~]# score=88.8

2. Read variable contents

Read variable contents:$
Read method: $variable name

Variable content readout
[root@www ~]# echo $name
baism
[root@www ~]# echo $school
ayitula
[root@www ~]# echo $age
30
[root@www ~]# echo $score
88.8

3. Cancel variable

[root@www ~]# unset name
[root@www ~]# echo $name

6, shell array

1. Basic array

Array allows users to assign multiple values at one time. When data needs to be read, it can be easily read through index call.
Array syntax
Array name = (element 1, element 2, element 3...)
Array readout

${Array name}[Indexes]
By default, the index is the queued number of elements in the array. By default, the first one starts from 0

Array assignment
Assign one value at a time

array0[0]='tom'
array0[1]='jarry'
array0[2]='natasha'

Assign multiple values at a time

# array2=(tom jack alice)
# array3=(cat /etc/passwd) I want to assign each line in the file as an element to array array3
# array4=(ls /var/ftp/Shell/for*)
# array5=(tom jack alice "bash shell")

Accessing array elements

# echo ${array1[0]} accesses the first element in the array
# Echo ${array1 [@]} accesses all elements in the array, which is equivalent to echo ${array1 [*]}
# echo ${#array1[@]} counts the number of array elements
# echo ${!array2 [@]} gets the index of the array element
# echo ${array1[@]:1} starts with array subscript 1
# echo ${array1[@]:1:2} accesses two elements starting with the array subscript 1

Traversal array

The default array is traversed by the number of array elements
[root@www ~]# echo ${array1[0]}
pear
[root@www ~]# echo ${array1[1]}
apple
[root@www ~]# echo ${array1[2]}
orange
[root@www ~]# echo ${array1[3]}
peach

2. Associative array

Associative array allows users to customize the index of the array, which is more convenient and efficient.
Define associative arrays

Declare associative array variables
# declare -A ass_array1
# declare -A ass_array2

Associative array assignment

Method 1: assign one value at a time
 Array name[Indexes]=Variable value
# ass_array1[index1]=pear
# ass_array1[index2]=apple
# ass_array1[index3]=orange
# ass_array1[index4]=peach

Method 2: assign multiple values at one time
# ass_array2=([index1]=tom [index2]=jack [index3]=alice [index4]='bash shell')

Accessing array elements

# echo ${ass_array2[index2]} accesses the second argument in the array
# echo ${ass_array2 [@]} accesses all the elements in the array, which is equivalent to echo ${array1 [*]}
# echo ${#ass_array2[@]} get the number of array elements
# echo ${!ass_array2 [@]} gets the index of the array element

Traversal array

Traversal through the index of array elements,For associative arrays, you can traverse through the index of array elements
[root@www ~]# echo ${ass_array2[index1]}
tom
[root@www ~]# echo ${ass_array2[index2]}
jack
[root@www ~]# echo ${ass_array2[index3]}
alice
[root@www ~]# echo ${ass_array2[index4]}
bash shell

3. Case sharing - student information system

/bin/bash
for ((i=0;i<3;i++))
   do
      read -p "Input No $((i + 1))Personal name: " name[$i]
      read -p "Input No $[$i + 1]Age: " age[$i]
      read -p "Input No`expr $i + 1`Personality type: " gender[$i]
done
clear
      echo -e "\t\t\t\t Student inquiry system"
while :
   do
      cp=0
      #echo -e "\t\t\t\t student query system"
      read -p "Enter the name to query: " xm
      [ $xm == "Q" ]&&exit
      for ((i=0;i<3;i++))
         do
              if [ "$xm" == "${name[$i]}" ];then
                  echo "${name[$i]} ${age[$i]} ${gender[$i]}"
                  cp=1
              fi
      done
      [ $cp -eq 0 ]&&echo "not found student"
done

Note: the above cases are from the UP main Python community of station B. It is better to eat them together with blogs and videos
shell script video link: Shell script

Topics: Python Linux Operation & Maintenance