当前位置:网站首页>[shell] summary of common shell commands and test judgment statements
[shell] summary of common shell commands and test judgment statements
2022-07-07 06:19:00 【alwaysrun】
List of articles
Shell Both a connection user and Linux Kernel program , It's another management Linux The script language of the system .
shell command
linux Various commands are provided under , Easy to handle .
adopt &&
And ||
Multiple commands can be combined and executed :
command1 && command2
: Only command1 Successful implementation ( The return result is 0) when , Will execute command2;command1 || command2
: Only command1 Execution failure ( The returned result is not 0) when , Will execute command2;adopt
{}
You can send multiple commands ( One command per line , Or split the command with a semicolon ) Form a command group ( Equivalent to an order );[ -e 2.txt ] && { echo 2.txt echo exists } || { echo 2.txt echo not exts; echo 33 } # Execution results : 2.txt not exts 33
content
cat
cat Used to display the contents of a text file ( Show all at once ):
cat [options] file
-n
: Number all lines of output ( Show line number in front )-b
: For all output Non empty line Number ( Show line number in front )-E
: The end of each line shows $( Indicates carriage return )
head
head Display the first few lines of the file ( Default display 10 That's ok )
head [options] file
-n k
: Before display k That's ok ( if k<0, Said the last k Line not displayed , The rest shows );-c k
: Before display k Bytes ( if k<0, Said the last k Line not displayed , The rest shows );-v
: Show the file name first , Then display the content
# Show the first two lines
head -n 2 test.sh
# Show all rows except the last two rows
head -n -2 test.sh
tail
tail Used to view the data at the end of the file
tail [options] file
-f
: Cyclic reading , Automatically read when the file is updated ;-f -s=m
: Every time m Seconds to update ( Read new changes );
-n k
: Show the last k That's ok ( Default 10 That's ok );-n +k
: According to the first k Line to end ;
-v
: Show the file name first , Then display the content ;
echo
echo Is to show the following content ( Default with line feed );
Output content without line breaks (-n)
# first And second In a row
echo -n "first" > 1.txt
echo "second" > 1.txt
Output content with control character ( At this time must be Use quotation marks around )
# first There is a blank line after
echo -e "first\n" > 1.txt
Text processing
In all valid lines ( Non empty , Non comment ) Add a prefix at the beginning of the line , And merge into one line :
cat test.txt | awk '!(!NF || /^#/){print "prefix",$0}' | tr -t ['\n'] [' ']
grep
grep You can search one or more files for a specific character pattern ( It can be a single character 、 character string 、 Words or sentences ).
grep [ Options ] ' Search string ' file
Options | meaning |
---|---|
-c | List only the number of lines in the file that contain the schema . |
-i | Ignore the case of letters in the mode . |
-l | List file names with matching lines . |
-n | List the line number at the beginning of each line . |
-v | List rows that do not have matching patterns . |
-w | Search the expression as a complete single character ( Match the whole word ) |
Wildcards are available in search strings :
wildcard | function |
---|---|
c* | Will match 0 individual ( That is, blank ) Or more characters c(c For any character ). |
. | Will match any character , And can only be one character . |
[xyz] | Match any one of the characters in the formula brackets . |
[^xyz] | Matches all characters except those in square brackets . |
^ | Lock the beginning of the line . |
$ | Lock the end of the line . |
sed
sed Process files according to script commands ( Read the contents of each line in turn and operate ), It is mainly used for data selection 、 Replace 、 Delete 、 Newly added .
sed [ Options ] [ Script command ] file
Options | meaning |
---|---|
-e | Appoint sed Edit command ; Multiple commands must be accompanied -e, Such as :-e 's/first//g; s/second//g' , Replace two at the same time |
-f | Appoint sed Edit the file of the command ( The command comes from the file ) |
-n | Silent mode ( Show only those changed lines ), Otherwise, everything will be displayed |
-i | Modify the source file directly |
Designated line : Script commands can specify the lines to be processed ( Each line will be processed by default )
line command
# perhaps , Multiline command
line{
command
}
- Line number from 1 Start ;
- Multiple lines are separated by commas : Such as
m,n
, Presentation operation [m,n] That's ok ; $
Indicates the end of the file : Such as2,$
, Indicates that the operation starts from 2 All the lines at the beginning of the line ;$=
Number of lines
# Show 1~3 That's ok
sed -n '1,3p' test.sh
# Show the total number of rows
sed -n '$=' test.sh
Match lines : You can also specify the row that handles matching ( Lines that meet text matching )
/pattern/ command
- Multiple matches are always separated by commas : Such as
/pattern1/,/pattern2/ command
# Show that echo The line of
sed -n '/echo/p' test.sh
# Show all for loop
sed -n '/for/,/done/p' test.sh
Replace
Replace the command , use replacement Replace pattern:
s/pattern/replacement/flags
flags | function |
---|---|
n | 1~512 Number between , Indicates the number of times the specified string to be replaced appears before it is replaced ; |
g | Replace all matched contents in the data , without g, Then the replacement operation will only be performed when the first matching is successful |
p | Lines that match the pattern specified in the replace command are printed . This tag is usually associated with -n Use options together . |
w file | Writes the contents of the buffer to the specified file In file ; |
& | Replace with what regular expressions match ; |
\n | Matching first n Substring , The substring was before pattern of use () Appoint . |
\ | escape ( The escape substitution section contains :&、\ , And the path separator /). |
Save to a new file after replacement :
sed 's/test/trial/gw test.txt' data.txt
Delete
adopt d command , Delete matching rows ; If you delete 1~3 That's ok :
sed '1,3d' test.sh
add rows
Before specifying the line (i) Or after the line (a) Add a line :
a( or i)\ Append row
- Oblique line
\
Omission , But if you add text that starts with a space , Must be separated by a slash
Add content after line :
# After the second line ( The third line ) Add a row ( The content is hello)
sed '2a hello' test.sh
# stay 2~5 After line (3,5,7,9) add to " hello"
sed '2,5a\ hello' test.sh
Row substitution
Replace the line that meets the condition :
c\ New line
# hold 2~5 Line delete , Then add a new line " hello"
sed '2,5c\ hello' test.sh
Character substitution
hold in Each character in , Replace with out The characters in ( Corresponding position replacement ,in And out Be of equal length )
y/inchars/outchars/
Replace lowercase with size
# Put three characters f、o、r Change to capital
sed 'y/for/FOR/' test.sh
Print lines that meet the addition ( Generally speaking, it is related to -n Parameters used together ):p
# Print 1~3 That's ok
sed -n '1,3p' test.sh
Writing documents
Write the contents to the specified file :
w file
hold 1~3 Line to write a new file :
sed -n '1,3w new.sh' test.sh
Insert file
Insert the contents of the file into the specified location
r file
hold new.sh End of inserted file :
sed '$r new.sh' test.sh
Exit command
adopt q command , You can exit at the specified position ( Do not process subsequent lines ).
Just replace before 10 That's ok :
sed 'y/for/FOR/; 10q' test.sh
Multiline command
sed There are special commands for handling multiline text ( All in capitals ); To search for cross line words , You have to deal with multiple lines together :
N
: After finding the qualified rows , Automatically read the next line ; The two lines are grouped together and treated as a whole ;D
: Delete a row in a multiline group .P
: Print a line in a multiline group .
Include for The row of is merged with the next row :
sed -n '/for/{N; s/\n//; p}' test.sh
awk
awk Command to scan the file line by line , Find the line that contains the target text , If the match is successful , Then the user's desired action will be performed on that line .
awk [ Options ] ' Script command ' file name
Options | meaning |
---|---|
-F fs | Set the separator to fs; The default separator is space or tab For example, take the dot as the separator awk -F. '{print $1}' At the same time “.” and “/” As a separator -F[./] |
-f file | Read script instructions from files |
-v var=val | Before executing the process , Set a variable var, The initial value of the device is val. |
Script commands consist of modes and operations ( be located In braces The order of ; Multiple lines are divided directly with semicolons : Mode or condition { operation }
) Two parts ; The mode can be :
- Regular expressions : The string must be enclosed with a backslash (
/ Match content /
); - Relationship expression : Use operators to operate , It can be a comparison test of strings or numbers ;
- Pattern matching expressions : Use operators
~
( matching ) and!~
Mismatch ; - The complete command is given by :BEGIN Sentence block ,pattern Sentence block ,END Sentence block , Three step composition ( Each part is optional ):
- BEGIN Sentence block : Execute before reading the row ( Only once ); Suitable for variable initialization , Print header and other operations ;
- pattern Sentence block : Read every line , perform pattern command ; If ignored , Directly print the line content ;
- ND Sentence block : Execute after reading all rows ( Only once ); It is suitable for printing results or summarizing information .
example :
$ awk 'END{print NR}' test.txt # Get the number of lines in the file
$ awk 'END{print $0}' test.txt # Print the last line
$ awk '/^$/ {print "Blank line"}' test.txt # Print blank lines
$ awk 'NR < 5 {print $0}' # Print the first four lines
$ awk 'NR==1,NR==4 {print $0}' # Print the first four lines
$ awk '/linux/ {print $0}' # The print contains linux The line of
$ awk '!/linux/ {print $0}' # Printing does not include linux The line of
# Logical operation &&,||,!
awk -F: '!($1~/root/ || $3<15)' /etc/passwd # Divide by colons , Not ( Field 1 by root, And field three is less than 15)
# Get all valid rows ( Non empty , Non comment )
cat test.txt | awk '!(/^$/ || /^#/){print "prefix-",$0}'
# perhaps :!NF Indicates that there is no field ; Use if when , Put it on {} in
cat test.txt | awk '{if(!NF || /^#/){next} {print "prefix-",$0}}'
Output
print Each parameter can be output in turn , It will wrap itself ;
printf Formable output ( similar C Language ); Default no line breaks , To add line breaks manually :
printf "|%-15s| %d | %f |\n", $1,$2,$3
next
next Indicates skipping the current line , And ignore all subsequent statements
# Output even lines ( When skipping the current line , hinder print The line of will not execute )
awk 'NR%2==1{next}{print NR,$0;}' test.sh
getline
Read in the next line ( Because the current line has been automatically read ,getline Equivalent to interlaced reading )
# Output even lines ( When skipping the current line , hinder print The line of will not execute )
awk '{getline; print NR,$0}' test.sh
Built-in variables
awk Command operation , You can use built-in variables :
- $n : Current record ( That's ok ) Of the n A field ( from 1 Start );
- $0 : The text content of the current line .
- NR : Represents the number of records , Corresponding to the current line number during execution ;
- FNR : Same as NR, When there are multiple files, it is relative to the current file .
- NF : Represents the number of fields ( How many fields can the current row be split into );
!NF
It can be used to judge whether it is an empty line - FS : Field separator ( Default to space or tab stop ) And "-F" The same effect ;
- OFS : Output field separator ( The default is a space )
- RS : Record separator ( Default newline );
- ORS : Output record separator ( Default newline );
- FILENAME : The name of the current input file ;
- OFMT : Digital output format ( The default value is %.6g);
Split output with semicolon ( Output the first two fields of each line ):
awk -v OFS=";" '{print $1,$2}' test.sh
String function
awk The following string processing functions can be used in the command :
length(string)
: Return stringstring
The length of .index(string, search_string)
: returnsearch_string
In stringstring
Where in .split(string, array, delimiter)
: Withdelimiter
As a separator , Split stringstring
, Store the generated string in the arrayarray
.substr(string, start-position, end-position)
: Return stringstring
China and Israelstart-position
andend-position
As a substring of start and end positions .sub(regex, replacement_str, string)
: Regular expressionsregex
Replace the first match withreplacment_str
.gsub(regex, replacement_str, string)
: andsub()
similar . But this function replaces the regular expressionregex
Everything that matches .match(regex, string)
: Check regular expressionsregex
Whether it can be in the stringstring
Find a match in . If you can find , Return non 0 value ; otherwise , return 0.match()
There are two related special variables , NamelyRSTART
andRLENGTH
. VariableRSTART
Contains the starting position of the matching content , VariablesRLENGTH
Contains the length of the matching content .
find
find Used to search for files
Press file name
Press file name ( Support for wildcards ? And *
) Search for :
find route -name " file name "
find route -iname " file name " # Case insensitive
Such as , Search all in the current directory cpp file :
find . -name "*.cpp"
By file type
Search for files of the specified type :
find route -type type
- d: Catalog
- f: Ordinary documents
- l: Link to the file (link)
- s: socket file
- p: Pipeline files (pipe)
- b: Block device file
- c: Character device file
Search all ordinary files in the current directory :
find . -type f
By file size
Search according to the file size range :
find route -size [+,-][c,w,k,M,G]
- +: Greater than
- -: Say less than
c,w,k,M,G
: Each represents a byte 、 Double byte 、 thousand 、 mega 、 ji ;
Such as query 100~200 Byte size file :
find . -type f -size +110c -size -200c -ls
find . -type f -size 148c # The size is 148 Byte file
According to the modification date
According to the creation of the file 、 Modify or access the date to search :
find route -atime/-ctime/-mtime [-/+]n
- n Is the number , Meaning in n Within one day before Changed documents .0 It means the document modified today ;
- +n: List n Days ago ( Not included n The day itself ) Changed documents ;
- -n: List n Within days ( contain n The day itself ) Changed documents ;
Such as querying the files created today :
find . -ctime 0
Combination to find
By combining multiple conditions , More complex searches can be constructed :
- -a: and
- -o: or
- -not:
Such as querying the file created today ( Folders are not included )
find . -type f -a -ctime 0
Find depth
Search depth can limit the number of levels of search directory
find route -maxdepth/-mindepth n
- -maxdepth: stay <=n Search in the layer directory (1 Represents the current layer );
- -mindepth: stay >=n Search in the layer directory (1 Represents the current layer );
In the current directory , And its lower directories ( Search only on both sides )
find . -maxdepth 2
find -exec
coordination -exec Parameters , You can perform further operations on the queried files
find route How to find it -exec shell command {} \;
- Command to
\;
end ; {}
Indicates the file name found ;
Display the details of the found file :
find . -type f -exec ls -l {} \;
lookup passwd Whether there is root:
find /etc -name "passwd*" -exec grep "root" {} \;
tr Character processing
tr(translate Abbreviation ) Mainly used to compress repeated characters , Delete the control characters in the file and perform character conversion .
tr [OPTION]... SET1 [SET2]
-s
: Compress repeated characters ; Compress SET1 Specifies the character ( duplicate removal )-cs
: Compress divide SET1 All characters except those specified in ( duplicate removal )
$ echo 'aaaa111bbbb22aaa3' | tr -s [ab] a111b22a3 $ echo 'aaaa111bbbb22aaa3' | tr -cs [ab] aaaa1bbbb2aaa3 # Remove empty lines from the file cat test.txt | tr -s ['\n']
-d
: Delete character ; Delete SET1 The characters specified in-cd
: Delete SET1 All characters except those specified in
$ echo 'aaaa111bbbb22aaa3' | tr -d [ab] 111223 # Delete non characters ( And keep line breaks ) $ echo 'aaaa111bbbb22aaa3' | tr -cd [ab'\n'] aaaabbbbaaa
-t
: Replace character , take SET1 Chinese characters use SET2 Replace the character in the corresponding position# toggle case $ echo 'aaaa111bbbb22aaa3' | tr -t [a-z] [A-z] AAAA111BBBB22AAA3 # All rows are merged into one row cat test.txt | tr -t ['\n'] [' ']
-c
: Complement replacement , use SET2 Replace SET1 in Not included The characters of# Replace the number with # # if SET Not in the middle '\n', Then the end newline character will also be replaced , The end will be ##, And don't break lines $ echo 'aaaa111bbbb22aaa3' | tr -c [ab'\n'] '#' aaaa###bbbb##aaa#
Character set
SET Chinese character set , The required characters can be listed separately , Can also pass -
Specified scope , And using predefined sets :
\NNN Character of octal value NNN (1 to 3 Characters that are octal values )
\\ The backslash
\a Ctrl-G Ring tone
\b Ctrl-H Back space
\f Ctrl-L Line break
\n Ctrl-J New line
\r Ctrl-M enter
\t Ctrl-I tab key
\v Ctrl-X Horizontal tabs
[CHAR*] in SET2, copies of CHAR until length of SET1
[CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0
[:alnum:] All the letters and numbers
[:alpha:] All the letters
[:blank:] Horizontal tabs , Blank, etc
[:cntrl:] All control characters
[:digit:] All the numbers
[:graph:] All printable characters , Do not include spaces
[:lower:] All lowercase characters
[:print:] All printable characters , Including Spaces
[:punct:] All punctuation characters
[:space:] All horizontal or vertical blanks
[:upper:] All capital letters
Count characters
Count the number of midpoint in the variable :
- Delete all characters except dot ;
- Count characters ;
#!/bin/bash
TAG_TEST=1.2.3
BUILD_NO=20220612
echo $TAG_TEST
COUNT=$(echo $TAG_TEST | tr -cd "." | wc -c)
if [ $COUNT -eq 2 ]; then
echo $TAG_TEST.$BUILD_NO >VERSION
elif [ $COUNT -eq 3 ]; then
echo $TAG_TEST >VERSION
else
echo "invalid Tag echo $TAG_TEST"
exit -1
fi
cat VERSION
seq Sequence
seq Something for outputting serialization :
seq [ Options ]... mantissa
seq [ Options ]... characteristic mantissa
seq [ Options ]... characteristic The incremental mantissa
Options :
-f fmt
: Specify the format ( similar printf);-s str
: Use str As a separator ;-w
: Add before column 0, Make the width the same ;
$ seq -s '#' 5
1#2#3#4#5
$ seq -w 1 10
01
...
10
xargs
xargs
The command is to convert standard input into command line parameters ; In pipeline operation (|
) when , The connection cannot receive the command of pipeline parameter ( That is, the command cannot be from stdin Receive input parameters directly , Such as ls etc. ).
Command format ( Default to Spaces and newlines
As a separator , Pass each part as a parameter to [command] command ):
xargs [-options] [command]
-L n
: Appoint n Rows form a parameter , Pass to [command] command ;-n n
: Appoint n Items form a parameter , Pass to [command] command ; Such as , Three parameters form a group :$ echo {1..9} | xargs -n 3 echo 1 2 3 4 5 6 7 8 9
-I
: Replace the specified string with parameters ( And at this time, the separator is newline )$ echo {1..9} | xargs -I num bash -c "echo num; echo num" 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
Looking to s Opening file / Folder , And output its details :
find . -maxdepth 1 -name "s*" | xargs ls -l
shell Script
shell Scripts are usually written as .sh
As extension , Which one is used in the first line shell Parser , With test.sh For example :
#!/bin/bash
echo "Hello World !"
perform :
- Direct execution ;
chmod a+x test.sh
: Add execute permission ;./test.sh
: Execute the script ;
bash test.sh
: Make it clear that bash The parser executes , And test The script file does not need execution permission ;
Variable
The value of each variable is a string , Whether or not you use quotation marks when assigning values to variables , Values are stored as strings .
There are three ways to define variables :
name=value
name='value'
name="value"
- If there are spaces in variables , You have to use quotation marks ;
- Single quote
' '
When enclosing the value of a variable , Original output ; - Double quotation marks
" "
When enclosing the value of a variable , Output will be done first Parse the variables and commands inside ;
Variables are deleted through unset command ( After deletion, it cannot be used again ):
unset name
Assign command results to variables
Assign the execution result of the command to the variable , There are two common ways :
variable=`command` # Cannot nest directly
variable=$(command) # Can be nested
Special variables
Variable | meaning |
---|---|
$0 | File name of the current script |
$n | Parameters passed to a script or function .n Indicates the number of parameters . Such as , The first parameter is $1, The second parameter is $2. |
$# | Number of arguments passed to script or function . |
$* | All parameters passed to a script or function . |
[email protected] | All parameters passed to a script or function . |
$? | Exit status of last command , Or the return value of the function . commonly 0 For success , Others are failures ; |
$$ | At present Shell process ID. about Shell Script , It's the process of these scripts ID. |
$ and [email protected] The difference between *
$* and [email protected] Represents all parameters passed to a function or script , Not double quoted (" “) When enclosed , Are subject to ”$1" “ 2 " … " 2" … " 2"…"n” Output all parameters in the form of ; When they are double quoted (" ") When enclosed :
- “$*” All parameters will be taken as a whole , With "$1 $2 … $n" Output all parameters in the form of ;
- “[email protected]” Separate parameters , Still with "$1" “ 2 " … " 2" … " 2"…"n” Output all parameters in the form of .
The following output shows the difference between the two ( When enclosed in quotation marks ):
#!/bin/bash
echo "print each param from \"\$*\""
for var in "$*"
do
echo "$var"
done
echo "print each param from \"\[email protected]\""
for var in "[email protected]"
do
echo "$var"
done
# $ test.sh a b c d
# print each param from "$*"
# a b c d
# print each param from "[email protected]"
# a
# b
# c
# d
Variable substitution
Variable substitution can be based on the state of the variable ( Is it empty 、 Whether to define, etc ) To change its value
form | explain |
---|---|
${var} | The original value of a variable |
${var:-word} | If the variable var Is empty or has been deleted (unset), Then the return word, But it doesn't change. var Value . |
${var:=word} | If the variable var Is empty or has been deleted (unset), Then the return word, And will var Is set to word. |
${var:?message} | If the variable var Is empty or has been deleted (unset), Then send the message message Send to standard error output , Can be used to detect variables var Whether it can be assigned normally . If this substitution appears in Shell Script , Then the script will stop running . |
${var:+word} | If the variable var Defined , Then the return word, But it doesn't change. var Value . |
character string
String index from 0 Start .
expression | meaning |
---|---|
${#str} | $str The length of |
${str:position} | stay $str in , From the position position Start extracting substrings |
${str:position:length} | stay $str in , From the position position Start extraction with a length of length The string of |
${str#substr} | Dependent variable $str Of open head , Delete the shortest match substr The string of |
${str##substr} | Dependent variable $str Of open head , Delete the longest match substr The string of |
${str%substr} | Dependent variable $str Of junction tail , Delete the shortest match substr The string of |
${str%%substr} | Dependent variable $str Of junction tail , Delete the longest match substr The string of |
${str/substr/newstr} | Use newstr Instead of the first matching substr |
${str//substr/newstr} | Use newstr Instead of all matching substr |
${str/#substr/newstr} | Replace the beginning : If $str With substr start , Then use newstr Replace |
${str/%substr/newstr} | Replace end : If $str With substr ending , Then use newstr Replace |
explain :"$substr” It could be a Regular expressions .
Conditions for testing
shell The logical operation in the script passes [ express ]
Realized , Be careful
[]
And test expressions There should be a space between ;- Put it in the judgment statement if Isochronous , Also pay attention to the space in the middle ;
- Variables need to use Enclosed in quotation marks Come on ;
- String comparison , Double brackets are recommended
[[ ]]
: Double brackets , Variables are automatically processed as a whole ;
Three types of tests :
- [ “$A” = 123 ]: Is a string test , Determine if it's a string "123".
- [ “$A” -eq 123 ]: It's an integer test , Judge whether it is a number 123.
- [ -e “$A” ]: It's file testing , Judge documents "123" Whether there is .
Double brace [[ ]]
And single brackets []
difference :
- Used in double brackets
&&
and||
Represents logic and logical or ; And in single brackets-a
and-o
Represents logic and logical or ; - Double brackets support string matching , use =~ Operator support shell Regular expression of ;
- Matching characters can be used in double brackets : Such as
[[ hello == hell? ]]
, The result is true
Number comparison
Only numbers are supported ( Or a string whose value is a number )
Operator | explain | give an example |
---|---|---|
-eq | Check whether two numbers are equal , Equal return true. | [ $a -eq $b ] return true. |
-ne | Check whether two numbers are equal , Unequal return true. | [ $a -ne $b ] return true. |
-gt | Check whether the number on the left is greater than that on the right , If it is , Then return to true. | [ $a -gt $b ] return false. |
-lt | Check if the number on the left is less than the number on the right , If it is , Then return to true. | [ $a -lt $b ] return true. |
-ge | Check whether the number on the left is greater than that on the right , If it is , Then return to true. | [ $a -ge $b ] return false. |
-le | Check whether the number on the left is less than or equal to the number on the right , If it is , Then return to true. | [ $a -le $b ] return true. |
[ 5 -ne 3 ]
return true Square brackets and variables and variables and operators There needs to be a space between
String comparison
Only for string comparison
Operator | explain | give an example |
---|---|---|
= | Checks if two strings are equal , Equal return true. | [ $a = $b ] return false. |
!= | Checks if two strings are equal , Unequal return true. | [ $a != $b ] return true. |
-z | Check if the string length is 0, by 0 return true. | [ -z $a ] return false. |
-n | Check if the string length is 0, Not for 0 return true. | [ -z $a ] return true. |
str | Check if the string is empty , Not empty return true. | [ $a ] return true. |
Such as , With a="test" For example
[ -z $a ] # return false
[ $a ] # return true
File test
Detect various attributes of the file
-b file
: Whether the file is a block device file , If it is , Then return to true.-c file
: Whether the file is a character device file , If it is , Then return to true.-d file
: Is the file a directory , If it is , Then return to true.-f file
: Whether the file is an ordinary file ( It's not a catalog , It's not a device file ), If it is , Then return to true.-r file
: Is the file readable , If it is , Then return to true.-w file
: Is the document writable , If it is , Then return to true.-x file
: Is the document executable , If it is , Then return to true.-s file
: Whether the file is empty ( Is the file size greater than 0), Not empty return true.-e file
: file ( Including directory ) Whether there is , If it is , Then return to true.-g file
: Whether the file is set SGID position , If it is , Then return to true-k file
: Whether the file has an adhesive bit set (Sticky Bit), If it is , Then return to true.-p file
: Whether the file is a named pipeline , If it is , Then return to true.-u file
: Whether the file is set SUID position , If it is , Then return to true.
Such as :
[ -d $file ] # Is a directory , return true
[ -e $file ] # File exists , return true
Boolean operation
Operator | explain | give an example |
---|---|---|
! | Non operation , Expression for true Then return to false, Otherwise return to true. | [ ! false ] return true. |
-o | Or operations , There is an expression for true Then return to true. | [ $a -lt 20 -o $b -gt 100 ] return true. |
-a | And operation , Both expressions are true To return to true. | [ $a -lt 20 -a $b -gt 100 ] return false. |
if sentence
shell Statements are separated by carriage return by default ( One line per statement ), If you want to enter multiple statements in one line, you can separate them by semicolons .
The test condition in the condition statement uses square brackets by default [ express ]
, Be careful The space in the middle ; Such as :
if [ $COUNT -eq 2 ]; then
# Command
fi
It has extended features for number and string judgment :
Double brace (( expression )): be used for Mathematical expression , Internally, it can be any mathematical calculation or comparison expression :
#COUNT=5 COUNT=2 if (($COUNT ** 2 > 10)); then ((var2 = $COUNT * 2)) echo "Large: $var2" else ((var2 = $COUNT + 10)) echo "Small: $var2" fi
Both brackets [[ expression ]]: be used for character string Handle ,expression Add a space on both sides :
if [[ "$a" > "$b" ]]; then echo "$a is large" elif [[ "$a" < "$b" ]]; then echo "$a is small" else echo "$a equal $b" fi
case sentence
There are many branches , And the judgment is simple , Use case in The sentence is more convenient :
case expression in
pattern1)
statement1
;;
pattern2)
statement2
;;
pattern3)
statement3
;;
……
*)
statementn
esac
pattern Represents a match pattern , It could be a number 、 A string , Even a simple regular expression ;case Will match one by one :
- When a pattern is successfully matched , The following corresponding statements will be executed , Until I met a double semicolon ;; Just stop ; And then the whole case The statement is executed ;
- If no pattern is matched , Then execute
*)
Subsequent statements ; - Except for the last branch , Each of the other branches must be preceded by
;;
ending ;
case Supported regular expressions :
*
Represents any string .[abc]
Express a、b、c Any one of the three characters . such as ,[15ZH] Express 1、5、Z、H Any of the four characters .[m-n]
From m To n Any character of . such as ,[0-9] Represents any number ,[0-9a-zA-Z] Represents letters or numbers .|
Indicates multiple selection , Similar to or operation in logical operation . such as ,abc | xyz
Represents a matching string “abc” perhaps “xyz”.
for sentence
for Circulatory :
- list for loop :
for Variable in Serial
- class C Style for loop :
for (())
list for loop
Execute the elements in the following list in turn .
Numbers
for a in {1..10} # Equivalent :for a in $(seq 1 10)
do
echo "number ${a}"
done
# Add unfamiliar
for a in {1..10..2} # Get only odd numbers
character string
list="Earth is the Home of Human! ";
for i in $list;
do
echo word is $i;
done
file
for file in $( ls ) # for file in ./*
do
echo "file: $file"
done
class C style
And C A cycle of similar language styles :
for ((i=1;i<=10;i++))
do
echo "num is $i"
done
边栏推荐
- POI excel export, one of my template methods
- LM小型可编程控制器软件(基于CoDeSys)笔记二十三:伺服电机运行(步进电机)相对坐标转换为绝对坐标
- You don't know the complete collection of recruitment slang of Internet companies
- Check Point:企业部署零信任网络(ZTNA)的核心要素
- C面试24. (指针)定义一个含有20个元素的double型数组a
- Ideas of high concurrency and high traffic seckill scheme
- Apple CMS V10 template /mxone Pro adaptive film and television website template
- Markdown displays pictures side by side
- [FPGA tutorial case 14] design and implementation of FIR filter based on vivado core
- How to keep accounts of expenses in life
猜你喜欢
力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
直击2022ECDC萤石云开发者大会:携手千百行业加速智能升级
Say sqlyog deceived me!
从“跑分神器”到数据平台,鲁大师开启演进之路
Sequential storage of stacks
关于STC单片机“假死”状态的判别
深度聚类:将深度表示学习和聚类联合优化
[SOC FPGA] peripheral PIO button lights up
Jstat of JVM command: View JVM statistics
Laravel uses Tencent cloud cos5 full tutorial
随机推荐
Cf:c. column swapping [sort + simulate]
Jstack of JVM command: print thread snapshots in JVM
Oracle迁移中关于大容量表使用数据泵(expdp、impdp)导出导入容易出现的问题和注意事项
JVM monitoring and diagnostic tools - command line
Qt多线程的多种方法之一 QThread
蚂蚁庄园安全头盔 7.8蚂蚁庄园答案
Redis(二)—Redis通用命令
New Year Fireworks code plus copy, are you sure you don't want to have a look
基于ADAU1452的DSP及DAC音频失真分析
3428. Put apples
一名普通学生的大一总结【不知我等是愚是狂,唯知一路向前奔驰】
云加速,帮助您有效解决攻击问题!
一段程序让你明白什么静态内部类,局部内部类,匿名内部类
MFC BMP sets the resolution of bitmap, DPI is 600 points, and gdiplus generates labels
基于FPGA的VGA协议实现
ST表预处理时的数组证明
Value range of various datetimes in SQL Server 2008
对称的二叉树【树的遍历】
进程间通信之共享内存
Convert numbers to string strings (to_string()) convert strings to int sharp tools stoi();