The Linux series that programmers must know and know-shell articles

The Linux series that programmers must know and know-shell articles

1. Shell basics

  • The shell is a command line interpreter, which provides users with an interface system-level program that sends requests to the Linux kernel in order to run the program
  • Users can use Shell to start, suspend, stop or write some programs
  • Shell is also a very powerful programming language, easy to write, easy to debug, and flexible.
  • Shell is a scripting language for interpretation and execution. Linux system commands can be called directly in Shell.

1.1 echo

  • Output command
  • -e: Activate the escape character
echo hello echo -e "a\tb" Copy code

1.2 Writing an execution shell

hello.sh

#!/bin/bash echo hello //Call the execution script through Bash sh hello.sh //Give execution permission, run directly chmod 755 hello.sh chmod u+x hello.sh ./hello.sh Copy code

1.3 Aliases

  • The command alias is the nickname
  • Temporarily effective
    alias cp="cp -i"
  • Write environment variable configuration file
    vi ~/.bashrc
  • source ~/.bashrc
  • Delete alias
    unalias alias

1.4 Order of Command Effectiveness

  • Absolute path or relative path
  • Alias
  • bash internal commands
  • according to
    $PATH
    The first command found in the directory search order defined by the environment variable

1.5 Command shortcuts

commandmeaning
ctrl+cForce termination of current command
ctrl+lClear screen
ctrl+aMove the cursor to the beginning of the command line
ctrl+eMove the cursor to the end of the command line
ctrl+uDelete from the cursor position to the beginning of the line

1.6 History commands

  • history [Options] [Save file of historical commands]
  • Options
    • -c Clear history command
    • -w Write the historical commands in the cache to the historical command save file~/.bash_history
  • Save 1000/etc/profile by default
    HISSIZE=10000

1.7 Call

  • Use the up and down arrows to call the previous history commands
  • use
    !n
    Repeat the nth historical command
  • use
    !!
    Repeat the previous command
  • use
    !character
    Repeat the last command starting with the string
history -c 1 echo 1 2 echo 2 3 echo 3 ! 2 !! !echo Copy code

1.8 Output redirection

1.8.1 Standard input and output

equipmentDevice file nameFile descriptorTypes of
keyboard/dev/stdin0Standard input
monitor/dev/stdout1Standard output
monitor/dev/stderr2Standard error output
Types ofsymboleffect
Standard output redirectionCommand> FileOutput the correct output of the command to the specified file or device in an overwritten manner
Standard output redirectionCommand >> FileIn addition, output the correct output of the command to the specified file or device
Error output redirectionCommand>FileOverwrite the error output of the command to the specified file or device
Error output redirectionCommand >> FileIn addition, output the error output of the command to the specified file or device
The correct output and error output are saved at the same timeCommand>File 2>&1Save the correct output and error output to the same file by way of overwriting
The correct output and error output are saved at the same timeCommand>File 2>>&1By appending, the correct output and error output are saved to the same file
The correct output and error output are saved at the same timeCommand &> FileSave the correct output and error output to the same file by way of overwriting
The correct output and error output are saved at the same timeCommand &>> FileBy appending, the correct output and error output are saved to the same file
The correct output and error output are saved at the same timeCommand>>File 1 2>File 2By way of overwriting, the correct output is appended to file 1, and the error output is appended to file 2.

1.8.2 Input redirection

  • wc
    The function of the command is to count the number of lines, words, and bytes in the specified file, and display and output the statistical results
  • command
    <
    File uses the file as input to the command
wc <a.txt; copy the code

1.9 Pipe symbol

1.9.1 Sequence execution of multiple commands

Multi-command executorformateffectCase study
;Command 1; Command 2Multiple commands are executed without any logical connection between the commandsecho 1;echo 2;
&&Command 1&&Command 2Logic and When command 1 is executed correctly, command 2 will be executed. When command 1 is executed incorrectly, command 2 will not be executed.echo 1&&echo 2;
\Command 1/Command 2Logic or when command 1 is executed incorrectly, command 2 will be executed. When command 1 is executed correctly, command 2 will not be executedecho 1\echo 2;
echo . 1; echo 2; echo . 1 && echo 2; echo . 1 || echo 2; duplicated code

1.9.2 Pipe symbol

  • The correct output of command 1 will be the operation object of command 2
  • Command 1|Command 2
ls/etc/| more netstat -an | grep ESTABLISHED | wc -l Copy code

1.9.3 Wildcard

  • Match file name and directory name
Wildcardeffect
?Matches an arbitrary character
*Match 0 or any character, that is, it can match any content
[]Match any character in the brackets
[-]Match any character in the brackets,-represents the range
[^]Match is not a character in brackets

1.9.4 Other symbols

symboleffect
''apostrophe. All special symbols in single quotes, such as $ and `, have no special meaning
""Double quotation marks, special symbols in double quotation marks have no special meaning, but the exception of $ `/has the meaning of calling variable values, quoting commands and escaping
``Backticks, expanded up are system commands
$()Same as backticks
#In a shell script, the line starting with # represents a comment
$The value used to call the variable
\Escape symbol
echo '$PATH' echo "$PATH" echo `ls` echo $(ls) echo -e "a\tb" Copy code

2. Variables

2.1 What is a variable

  • The amount that can be changed
  • Variables must start with a letter or underscore, and the name can only consist of letters, numbers and underscores
  • The length of the variable name must not exceed 255 characters
  • The variable name must be unique within the valid range
  • The default types of variables are strings

2.2 Classification of variables

  • String
  • Integer
  • Floating point
  • Date type

2.3 User-defined variables

  • The values of these variables are defined by themselves
  • Variable name cannot start with a number
  • There can be no spaces on the left and right sides of the equal sign

2.3.1 Define variables

name = "james" ; age = 10 ; copy the code

2.3.2 Output variable value

echo $ variable names Copy the code

2.3.3 Values are all strings by default

$ x = 1 $ y = 2 $ z = 3 $ k=$x+$y+$z $ echo $k 1 + 2 + 3 copy the code

2.3.4 Referencing variables when assigning values

m= "$x" 2 n=${x} 2 echo $m $n Copy code

2.3.5 set

  • Query all the variables that are in effect by default in the system, including system variables and custom variables
set | grep jamesCopy code

2.3.6 unset

  • Delete variable
unset a duplicated code

2.4 Environment variables

  • Environment variables are global variables, and custom variables are local variables
  • Custom variables will take effect in the current shell, and environment variables will take effect in the current shell and its subshells
  • This kind of variable mainly saves data related to the operating environment of the system
  • Variables can be customized, but the name and function of the environment variables that take effect on the system are fixed

2.4.1 Custom environment variables

export variable name = variable value export envname = Prod duplicated code

2.4.2 env

  • Only used to view environment variables, not local variables

    env | grep envNameCopy code

2.4.3 Commonly used environment variables

variable namemeaningExample
HOSTNAMECPU nameHOSTNAME=localhost
SHELLCurrent shellSHELL=/bin/bash
HISTSIZENumber of historical commandsHISTSIZE=1000
SSH_CLIENTIf the current operating environment is connected by SSH, the client IP will be recorded hereSSH_CLIENT=192.168.1.100 57596 22
USERCurrently logged in userUSER=root
echo $HOSTNAME echo $SHELL echo $HISTSIZE echo $SSH_CLIENT echo $USER Copy code

2.4.4 path

  • System search path
# echo $PATH /usr/lib/the Qt- 3.3/bin: /usr/ local/sbin: /usr/ local/bin: /sbin:/ bin: /usr/ sbin: /usr/ bin: /the root/ bin duplicated code

If you want to execute a custom script directly, or copy the file to the target directory, or add the directory where the script is located to the environment variable

PATH
In the path

/root/shells/hello.sh

#! /bin/ bash echo hello export PATH= "$PATH" : /root/ shells hello.sh Copy code

2.4.5 Language environment variables

  • Query the current system language
  • Pass in Linux
    locale
    To set the different language environments in which the program runs, locale is supported by ANSI C. The naming rule for locale is <language>_<region>.<character set encoding>, such as zh_CN.UTF-8, where zh stands for Chinese, CN stands for mainland China, and UTF-8 stands for character set.
  • LANG: Variables that define the subject language family of the system
locale LANG=zh_CN.UTF- 8 echo $LANG Copy code

2.4.6 Chinese Support

  • Graphical interface can support Chinese
  • Third-party tools such as xshell have the correct language settings to support Chinese
  • The pure character interface in the virtual machine does not support Chinese

2.5 Positional parameter variables

  • This kind of variable is mainly used to pass parameters or data to the script. The variable name cannot be customized, and the variable function is fixed.
Positional parameter variableeffect
$nn is a number,0Represents the command itself,0 represents the command itself, 1-9Representative1To the first9Parameters,10The above parameters need to be enclosed in braces,Such as9 represents the 1st to 9th parameters, the parameters above 10 need to be enclosed in braces, such as {10}
$*This variable represents all the parameters in the command, $* regards all the variables as a whole
$@This variable also represents all the parameters in the command line, but $@ distinguishes each parameter
$#This variable represents the number of all parameters in the command line

sum.sh

#! /bin/ bash num1=$ 1 num2=$ 2 sum=$((num1+num2)) echo $sum sum.sh SH . 3 . 4 duplicated code

vi for.sh

#! /bin/ bash for i in "$@" do echo "i=$i" done SH for .sh . 1 2 . 3 I = . 1 I = 2 I = . 3 duplicated code

vi for2.sh

#! /bin/ bash for i in "$#" do echo "i=$i" done for2.sh SH . 1 2 . 3 I = . 1 2 . 3 duplicated code

vi for3.sh

#! /bin/ bash echo "$ #" SH for3.sh 1 2 3 3 Copy the code

2.6 Predefined variables

  • It is a variable that has been defined in the script, the variable name cannot be customized, and the function of the variable is also fixed
Positional parameter variableeffect
$?The return status of the last executed command. 0 means correct execution, non-zero means incorrect execution
$$Process ID (PID) of the current process
echo $? echo $$ Copy code

2.7 read

read [options] [variable name]

Optionsmeaning
-pPrompt message, output prompt message while waiting for read input
-tSeconds: The read command will always wait for user input. Use this option to specify the waiting time
-nThe number of characters, the read command only accepts the specified number of characters, it will be executed
-sHide the input data, suitable for the input of confidential information
#! /bin/ bash read -p'please input your name:' -t 5 name echo -e "\n" read -p'please input you gender[m/f]:' -n 1 gender echo -e "\n" read -p'please input your password:' -s password echo -e "\n" echo $name,$gender,$password sh read.sh Copy code

3. Operator

  • Weak type and default string type

3.1 declare command

3.1.1 declare command

  • Used to declare variable types
  • declare [+/-] [options] variable name
Optionsmeaning
-Set the type attribute to the variable
+Cancel the type attribute of the variable
-aDeclare the variable as an array type
-iDeclare the variable as an integer
-xDeclare variables as environment variables
-rDeclare the variable as a read-only variable
-pDisplay the declared type of the specified variable
a = 1 b = 2 c=$a+$b echo $c 1 + 2 declare -ic=$a+$b //Declare as an integer echo $c 3 declare +ic //Cancel the type attribute of the variable c=$a+$b echo $c 1 + 2 declare -ic = "3" //Set the type attribute to the variable declare -pc //Display the declared type of the specified variable //declare -ic="3" //Declare environment variables declare -x kk = 1 set | grep kk //View all variables env | grep kk //View only system variables -rx DECLARE //read-only X = 2 //the bash: X: Readonly variable copy the code

3.1.2 Array

//Declared as an array type declare -a names; names[ 0 ]=zhangsan names[ 1 ]=lisi //Only the first element is printed by default echo ${names} zhangsan //Print the second element echo ${names[ 1 ]} lisi //Print all echo ${names[*]} zhangsan lisi Copy code

3.1.3 Declare environment variables

  • The final execution of export is
    declare -x
    command
  • declare -p
    Can view all types
export NAME=james declare -x NAME=james Copy code

3.1.4 Read-only attributes

declare -r gender=m gender=f -bash: gender: readonly variable Copy code

3.1.5 Query variable attributes

  • declare -p
    Query the attributes of all variables
  • declare -p
    Variable name query the attributes of the specified variable

3.2 Numerical calculation methods

  • As long as you specify the type when declaring a variable with declare, you can perform numerical operations

3.2.1 expr or let

    • There must be spaces on the left and right sides of the number, otherwise the whole block is output
num1= 2 num2= 3 sum=$(expr $num1 + $num2) echo $sum 5 sum2=$(($num1+$num2)) echo $sum2 5 sum3=$[$num1+$num2] echo $sum3 5 d=$(date) echo $d Copy code

3.2.2 Priority

= $ Result ((( . 1 + 2 ) * . 4/2 )) echo $result 6 copy the code

4. Environment Variable Configuration File

4.1 source command

  • After modifying the configuration file, you must log out and log in again to take effect. Use the source command to avoid logging in again
  • source configuration file
  • . Configuration File

4.2 Introduction to Environment Variable Configuration File

  • PATH, HISTSIZE, PS1, HOSTNAME and other environment variables are written into the corresponding environment variable configuration file
  • The environment variable configuration file mainly defines the system default environment variables that take effect in the system operating environment, such as
    PATH
    Environment variables that take effect when this file is logged in
pathDescription
/etc/profile
/etc/bashrc
~/.bash_profileWill only take effect for the current user
~/.bashrcWill only take effect for the current user

4.3 The function of the environment variable configuration file

4.3.1/etc/profile

  • Modify system variables here
cat/etc/profile | grep USER copy the code
variable namemeaning
USERusername
LOGNAMElog-in name
MAILemail address
PATHSearch path
HOSTNAMECPU name
umaskPermission mask
/etc/profile.d/star.sh

4.3.2 ~/.bash_profile

  • Modify here
    PATH
    path
  • Call ~/.bashrc

4.3.3 ~/.bashrc

  • Change alias here, configure alias
  • transfer
    /etc/bashrc

4.3.4/etc/bashrc

  • PS1
    The login prompt is modified here
  • umask
  • PATH
    variable
  • transfer
    /etc/profile.d/star.sh
    file

4.3.5. Other configuration files

4.3.5.1 Environment variable configuration file that takes effect upon logout
  • ~/.bash_logout
4.3.5.2 Script history
  • When the computer is properly exited, the history record will be written to the file
  • ~/.bash_history
4.3.5.3 Shell login information
  • Local terminal welcome message
    /etc/issue
  • Remote terminal welcome message
    /etc/issue.net
  • It can take effect regardless of remote or local
    /etc/motd
parametermeaning
\dCurrent system date
\sShow operating system name
\lDisplay the logged-in terminal number
\mDisplay the hardware architecture, such as i386, etc.
\nShow hostname
\oShow domain name
\rShow kernel version
\tDisplay current system time
\uDisplay the serial number of the currently logged in user
vi/etc/ssh/sshd_config Banner/etc/issue.net service sshd restart Copy code

4. Regular expressions

4.1 Concept

  • Regular expression is a grammatical rule used to describe character arrangement and matching mode
  • It is mainly used for string pattern segmentation, matching search and replacement operations

4.2 Wildcard

  • Wildcards are used to match file names that meet the conditions, and wildcards are an exact match.
  • ls find These commands do not support regular, only wildcards can be used
symbolmeaning
?Match any character
*Match any number of characters
[]Match a character in the range of brackets

4.3 Regular expressions

  • Regular expressions are used to match qualified strings in a file, which is a containment match.
  • Grep, awk, sed, etc. can support regular expressions

4.4 Metacharacters

alias grep = 'grep --color = auto ' duplicated code
MetacharactereffectExample
*Match the previous character 0 or any number of timesgrep 1* reg.txt
.Match any character except newlinegrep. reg.txt
^Match the beginning of the line. For example, ^hello will match the line starting with hellogrep ^a reg.txt
$Match the end of the line. For example, hello& will match lines ending in hellogrep a$ reg.txt
[]Matches any one character specified by the handle number, and only matches one character. For example. [aoeiu] matches any vowel, [0-9] matches any digit, [az][0-9] matches two characters consisting of a lowercase letter and a digitgrep ab[bc]c reg.txt
[^]Match any character except the characters in the brackets. For example, [^0-9] matches any non-digit character, [^az] matches any non-lowercase lettergrep a[^fg]c reg.txt
\Escape character, used to cancel the meaning of special symbolsgrep .$ reg.txt
{n}Indicates that the character before it appears exactly n times. For example, [0-9]{4} matches 4 digits, [1][3-8][0-9]{9} matches mobile phone numbergrep "a{1}" reg.txt
(n,)Indicates that the preceding character appears no less than n times. For example, [0-9]{2,} matches two or more digitsgrep "a{1,}" reg.txt
{n,m}Indicates that the character before it appears at least n times, and at most m times. For example, [az]{6,8} matches 6 to 8 lowercase lettersgrep "a{2,3}" reg.txt

4.5 cut

  • cut is used to extract a certain part of the text
  • cut [options] filename
    • -f column number, used to specify the column to be extracted
    • -d delimiter, split the column according to the specified delimiter, the default delimiter is TAB tab

Extract the username and the shell it uses

cat/etc/passwd | cut -f 1 , 7 -d: copy the code

4.6 printf

  • Output in prescribed format
  • printf output type output content
parametermeaning
%nsOutput string, n is a number refers to output several characters
%niOutput integer, n refers to output several numbers
%m.nfOutput floating-point numbers, m and n are numbers, referring to the number of integers and decimal places of the output, such as %6.2f represents the output of 6 digits, 2 decimals, and 4 integers
the printf "% S/T% S/T% S/T% S/T% S/T/S%/n-" $ (DF -H | grep/dev/Vdal) | Cut -f . 1 , . 5 copy the code

4.7 awk

  • awk'Condition 1{Action 1} Condition 2{Action 2}...' File name
  • Condition (Pattern)
    • Generally use relational expressions as conditions
    • x> 10 Determine whether the variable x is greater than 10
    • x >=10 greater than or equal to
    • x <=10 less than or equal to
  • Action
    • Formatted output
  • 0Whole line0 entire line 1 first column...
-H DF | grep/dev/Vdal | awk '{}. 5 Print $' | Cut -d '%' -f . 1 duplicated code

4.7.1 begin end

  • awk can intercept tabs and spaces correctly
  • begin print before all output
  • end print after all output
echo "" > numbers.txt awk 'the BEGIN {Print "Start"} END {print "End"}' numbers.txt copy the code

4.7.2 FS

  • Field Separator, field separator
awk 'the BEGIN {the FS = ":" Print $ {}. 1 "/T" $ 2}'/etc/the passwd duplicated code

4.7.3 Declare variables

numbers.txt

. 1 2 . 3 awk 'the BEGIN {SUM = SUM = SUM {0} + {Print the END $ SUM. 1}}' numbers.txt . 6 duplicated code

4.7.4 Multiple conditions

score.txt

zhangsan 91 is Li 81 wangwu 71 is awk '$ 2> {Print $ 90. 1 "/T Excellent"} $ 2> 80 {print $ 2 "/t Good"}' score.txt copy the code

4.7.5 NR

  • NR, which means the number of rows of data read after awk starts executing the program
awk '{Print NR, $ 0}' score.txt copy the code

4.7.6 OFS

  • OFS Out of Field Separator, output field separator
echo "I Love you" | awk 'the BEGIN {the FS = ""; the OFS = "-" Print $ {}. 1, $ 2, $}. 3' copy the code

4.8 sed command

  • sed is a lightweight editor, mainly used to select, replace, replace and add data
  • sed [options]'[action]' filename
  • All actions must be enclosed in single numbers
  • Type is similar to batch
    vi
    operating

4.8.1 Action

parametermeaningExample
aAppend, add one or more lines below each line or specified line
sed '1a newline' score.txt
cLine replacement, replace the original entire data line with the string after c
sed'c newline' score.txt
sString replacement, replace one string with another string, the format is "line range s/old string/new string/g"
sed '3s/lisi/lisisi/g' score.txt
iInsert, insert one or more rows in the current row
sed '1i newline' score.txt
dDelete the specified row
sed '1,2d' score.txt
pPrint, output the specified line
sed -n '2p' score.txt

4.8.2 Options

parametermeaningExample
-nGenerally, the sed command will output all data to the screen. If this option is added, only the processed lines will be output to the screen.
sed -n '2p' score.txt
-eAllow multiple sed editing commands to be applied to input data
sed -e's/91/92/g;s/81/82/g' score.txt
-iUse sed to modify the edited file directly instead of outputting it on the screen
sed -i '1i newline' score.txt

4.9 Sort command sort

  • sort [options] filename
  • Options
Optionsmeaning
-fIgnore casesort -f -t ":" -n -k 5,5/etc/passwd
-nSort by number, use string order by defaultsort -t ":" -n -k 3,3/etc/passwd
-rReverse sorting, default from small to largesort -r/etc/passwd
-tSpecify the separator, the default separator is a tabsort -t ":" -k 3,3/etc/passwd
-kn[,m]Sort according to the specified field range. Start from the nth field to the mth field, the default is to the end of the linesort -t ":" -k 3,3/etc/passwd
sort/etc/passwd sort -r/etc/passwd -t Sort ":" -k . 3 , . 3/etc/the passwd duplicated code

4.10 wc

  • wc [options] file name
Optionsmeaning
-lOnly count the number of rows
-wOnly allow words
-mOnly count the number of characters
wc wc.txtcopy code

5. Process Control

5.1 Conditional judgment

5.1.1 Judgment according to file type

Optionsmeaning
-dWhether the file exists and is a directory
-eDoes the file exist
-fWhether the file exists and is a normal file
-bWhether the file exists and is a block device file
-cWhether the file exists and is a character device file
-LWhether the file exists and is a linked file
-pWhether the file exists and is a pipeline file
-sWhether the file exists and is not empty
-SWhether the file exists and is a socket file
touch 1. txt test -e 1. txt [-e 1. txt] echo $? Copy code

exist.sh

[-e 1. txt ]&&echo "yes" || echo "no" yes [-e 11. txt ]&&echo "yes" || echo "no" no Copy code

5.1.2 Judging according to file permissions

Optionsmeaning
-rWhether the file exists and whether it has read permission
-wWhether the file exists and whether it has write permission
-xWhether the file exists, and whether it has execute permission
echo read> read.txt echo write> write.txt echo execute> execute.txt chmod u+w write.txt chmod u+x execute.txt [-r read.txt ]&&echo "read yes" || echo "no" [-w write.txt ]&&echo "write yes" || echo "no" [-x execute.txt ]&&echo "execute yes" || echo "no" Copy code

5.1.3 Comparison between two files

Optionsmeaning
File 1 -nt file 2Determine whether the modification time of file 1 is newer than that of file 2
File 1 -ot file 2Determine whether the modification time of file 1 is older than that of file 2
File 1 -ef file 2Determine whether the inode numbers of file 1 and file 2 are the same, which can be used to determine hard links
[write.txt -nt read.txt ]&&echo "write is older than read" || echo "no" [read.txt -ot write.txt ]&&echo "read is older than write" || echo "no" ln execute.txt execute2.txt [Execute.txt execute2.txt -ef] && echo "Execute and are execute2.txt The Same" || echo "NO" copy the code

5.1.4 Comparison between two integers

Optionsmeaning
Integer 1 -eq integer 2Determine whether integer 1 is equal to integer 2
Integer 1 -ne integer 2Determine whether integer 1 is not equal to integer 2
Integer 1 -gt integer 2Determine whether the integer 1 is greater than the integer 2
Integer 1 -lt integer 2Determine whether the integer 1 is less than the integer 2
Integer 1 -ge integer 2Determine whether the integer 1 is greater than or equal to the integer 2
Integer 1 -le integer 2Determine whether the integer 1 is less than or equal to the integer 2
[ 2 -eq 2 ]&&echo "2==2" || echo "no" [ 3 -ne 2 ]&&echo "2!=2" || echo "no" [ 3 -gt 2 ]&&echo "2>2" || echo "no" [ 1 -lt 2 ]&&echo "2<2" || echo "no" [ 2 -ge 2 ]&&echo "2>=2" || echo "no" [ 2 -le 2 ] && echo "2 <2 =" || echo "NO" copy the code

5.1.5 Judgment of character string

Optionsmeaning
-z stringDetermine whether the string is empty
-n charactersDetermine whether the string is non-empty
String 1 == string 2Determine whether string 1 is equal to string 2
String 1 != string 2Determine whether string 1 is not equal to string 2
name=james [-z "$name" ]&&echo "empty" || echo "not empty" [-n "$name" ]&&echo "not empty" || echo "empty" name2=james [ "$ Name" == "$ NAME2" ] && echo "equal" || echo "not equal" [ "$ name" ! = "$ NAME2" ] && echo "not equal" || echo "equal" copy the code

5.1.6 Multiple condition judgment

Optionsmeaning
Judgment 1 -a Judgment 2Logical and
Judgment 1 -o Judgment 2Logical OR
!judgmentLogical negation
[ 2 -gt . 1 -a . 3 -gt 2 ] && echo "Yes" || echo "NO" [ 2 -gt . 1 -a . 3 -gt . 4 ] && echo "Yes" || echo "NO" [ 2 -gt . 1 - O . 3 -gt . 4 ] && echo "Yes" || echo "NO" [! . 3 -gt . 4 ] && echo "Yes" || echo "NO" copy the code

5.2 Single branch if statement

  • if statement use
    fi
    end
  • [Conditional Judgment] is to use
    test
    The command is used for judgment, so there must be a space between the brackets and the conditional judgment
  • Then is followed by the program to be executed after meeting the conditions, which can be placed after [], separated by ;, or can be wrapped instead of;

5.2.1 Syntax

if [conditional judgment]; then Code body fi if [conditional judgment] then Code body fi if [ 2 -gt 1 ];then echo bigger; fi if [ 2 -gt 1 ] then echo bigger fi Copy code

5.2.2 Determine whether the current user is a root user

isRoot.sh

#! /bin/ bash user=$(whoami) user= `whoami` if [ "$user" == root] then echo "I am a root user" fi Copy code

5.3 Double branch if statement

5.3.1 Syntax

if [conditional judgment] then Code body 1 else code body 2 fi Copy code

5.3.2 Judge whether it is a directory

isDir.sh

#! /bin/ bash read -t 10 -p "Please enter a path" dir if [-d "$dir" ] then echo "$dir is a directory" else echo "$dir is not a directory" fi Copy code

5.4 Multi-branch if statement

5.4.1 Syntax

if [conditional judgment 1 ] then Code body 1 elif [Condition judgment 2 ] Code body 2 else code body 3 fi Copy code

grade.sh

#! /bin/ bash read -p "Please enter a score" grade if [ "$grade" -gt 90 ] then echo excellent elif [ "$grade" -gt 80 ] then echo good else echo bad fi Copy code

5.5 case statement

  • Both case and if are multi-branch judgment statements. If can judge multiple conditions, case can only judge one condition.

    5.5.1 Syntax

    case variable name in value 1 ) Code block 1 ;; Value 2 ) Code block 2 ;; *) Code block 3 ;; esac Copy code

case.sh

#! /bin/ bash read -p "yes or no?" -t 30 choose case $choose in "yes" ) echo'yes ' ;; "no" ) echo "No" ;; *) echo other ;; esac Copy code

5.6 for loop

5.6.1 Syntax

for variable in value 1 value 2 value 3 do Code block done Copy code

for.sh

#! /bin/ bash for i in 1 2 3 do echo $i done Copy code

5.6.2 Syntax

#! /bin/ bash for ((i = 1 ;i<= 10 ;i++)); do echo $(($i)); done Copy code

5.7 while loop

  • The while loop is an indeterminate loop, also called a conditional loop, as long as the conditional judgment is established, it will continue
while [conditional judgment] do Code block done Copy code

while.sh

#! /bin/ bash i = 1 result = 0 while [$i -le 100 ] do result=$(($result+i)) i=$(($i+ 1 )) done echo $result Copy code

5.8 until loop

  • Stop until the condition is not met

until.sh

#! /bin/ bash i = 1 result = 0 until [$i -gt 100 ] do result=$(($result+i)) i=$(($i+ 1 )) done echo $result Copy code

6. Functions

  • linux shell
    Functions can be defined by the user, and then can be called casually in the shell script
  • Can bring
    function fun()
    Definition, or directly
    fun()
    Definition without any parameters
  • Calling the function does not need to add
    ()

6.1 Simple functions

[ function ] funcName [()] { action; [ return int;] } start () { > echo start >} start #! /bin/ bash start () { echo start } start Copy code

6.2 Return value

  • Parameter return, you can display the addition: return return, if not added, the result of the last command will be used as the return value
sum () { > result=$(($ 1 +$ 2 )) > return $result >} sum4 2 3 echo $? 5 copy the code

6.3 Parameter description

Parameter handlingDescription
$#The number of parameters passed to the script
$*Display all parameters passed to the script as a single string
$@Same as $*, but use quotation marks and return each parameter in quotation marks
$$ID number of the current process running the script
$?Display the exit status of the last command. 0 means there is no error, any other value means there is an error

7. Shell combat

7.1 Matters needing attention

  • Add an interpreter at the beginning: #/bin/bash and comments
  • Naming suggestion rules: uppercase variable names, lowercase local variables, lowercase function names, the name reflects the actual effect
  • The default variable is global, the variable local is designated as a local variable in the function to avoid polluting other scopes
  • set -e
    Exit the script when it encounters a non-zero execution,
    set -x
    Print execution process
  • Writing scripts must be tested first and then on the production environment

7.2 Check the host survival status

ip.sh

#! /bin/ bash for IP in $@; do if ping -c 1 $IP &> /dev/null ; then echo "$IP is ok." else echo "$IP is wrong!" fi done ip.sh SH 127.0 .0 .1 duplicated code