1. The first line must specify the shell used: #!/bin/bash/2, Print command: Echo
-N: Suppress line breaks
3. Use command line parameters:
$#: The number of command-line arguments passed in the script
$*: All command-line parameter values, with a space between each parameter value (as a word processing)
[Email protected]: All command line parameter values (processed as multiple words)
$: Command the Province (shell file name)
$: First command-line argument
$: Second command-line argument
Gets the last parameter of the user input ${!#} cannot be used with ${$#}
4. Mathematical calculation:
Expr does mathematical calculations
To assign the result of the calculation to other variables, you need to add an inverse quote.
5. If statement:
if[condition] #condition前后都要有空格
Then
Commands
Else
Commands
Fi
If nesting:
If Command1
Then
Command2
Elif Command3
Then
Command4
Fi
6. Condition Comparison:
-eq Same
-ne different
-GT Greater than
-lt less than
-ge greater than or equal to
-le less than or equal to
-Z is empty
-N is not empty
7. String comparison:
STR1 = str2 Check if str1 is the same as str2
!=
<
>
-N str1 Check if str1 length is greater than 0
-Z str1 Check if str1 length is 0
8, file comparison:
-d file checks if file exists and is a directory
-e file checks if file exists
-F File checks if file exists and is a file
-r file checks if file exists and is readable
-S file checks if file exists and is not empty
-W file checks if file exists and is writable
-X file checks if file exists and is executable
-O file checks if file exists and is owned by the current user
-G file checks if file exists and whether the default group is the current user group
File1-nt file2 Check if file1 is newer than file2
File1-ot file2 Check if file1 is older than file2
#两个条件同时满足
If [Condition1] && [Condition2]
Then
Command1
Fi
#两个条件其中一个满足
If [Condition1] | | [Condition2]
Then
Command1
Fi
#取反
if [! condition]
Then
Command1
Fi
Double parenthesis:
((Command1)) #允许像C一样的操作
Case statement:
Case variable in
PATTERN1)
Command1;;
PATTERN2)
Command2;;
*) # * Number indicates other values
default commands;;
Esac
9. For statement:
Method 1:
for Var in list
Do
Commands
Done
Method 2:
for ((i = 0;i < 10;i++))
Do
Commands
Done
10. Read the data from the file:
file= "FileName"
For data in ' cat $file '
Do
echo "Data is $data"
Done
11. IFS: Changing the internal field delimiter
General usage:
Ifs_old= $IFS
ifs=$ ' \ n ':;
Code
ifs= $IFS _old
12. Get the files and sub-files in the current directory:
#for file in ' pwd '/* #通配, all files in the current directory
For file in ' find '
Do
If [-D "$file"]
Then
echo "$file is a directory"
Elif [-F "$file"]
Then
echo "$file is a file"
Fi
Done > Output.txt #重定义循环输出
13, getopts command: getopts optstring variable
Parameters:
Optstring: Option string
Variable: Parameters
If the option letter requires a colon after the parameter value
If you want to suppress output error messages, start the option string with a colon
Instance:
While Getopts ab:opt
Do
Case ' $opt ' in
A) echo "found–a option";;
b) echo "found–b option with value $OPTARG";;
Esac
Done
Options |
Describe |
Options |
Describe |
-A |
Show All Objects |
-N |
Use non-interactive (batch) mode |
-C |
Build Count |
-O |
Specify an output file to redirect the output |
-D |
Specify directory |
-Q |
Execute in quiet mode |
-E |
Expand objects |
-R |
Recursively process directories and files |
-F |
Specify a file to read data from |
-S |
Execute in silent mode |
-H |
Show Help for a command |
-V |
Generate verbose output |
-I. |
Ignore case |
-X |
Exclude and Reject |
-L |
Output of the number of raw growth |
-Y |
Set the answer to all questions Yes |
Table 13.1 Common Linux command-line options
14. Read user input:
Basic reading Read
Read if no variable is specified, the default is stored in the environment variable $reply
-P: A prompt can be specified directly in the Read command
-T: Specify a wait input time, usage-t
eg
If read–t 5–p "Plase input your Name:" Name #会输入到错误流 ...
Then
Echo $name
Else
Echo–e "\nyou is too slow"
Fi
-N: Specifies the number of characters entered and automatically ends the input when the number of characters specified in n is reached, followed by the number of characters to be entered directly after the use of-n
-S: User input is not displayed on the window, such as when entering a password
15. Redirect:
To redirect Stdeer and StdOut separately:
Eg:ls–al test1 test2 2> error.txt 1> right.txt
REDIRECT Stdeer and stdout to the same file: Redirect with &>
Temporary redirection:
Eg:echo "This was an error" >&2 #重定向到错误流
./bash.sh 2> Tmp.txt #重定向错误流到tmp
Permanent redirection: (Cannot switch back)
exec 1> File
EXEC 2> Errfile
Redefine input: (cannot switch back)
EXEC 0< Inputfile
REDIRECT File descriptor: (can switch back)
Save 1 (STDOUT) with the file descriptor 3
EXEC 3>&1
EXEC 1>file
echo "someing write to File"
EXEC 1>&3
Save 0 (STDIN) with the file descriptor 4
EXEC 4<&0
EXEC 0<file
While Read line
Do
Echo $line
Done
EXEC 0<&4
To close the file descriptor:
EXEC 3>&-
List Open file descriptors:
/usr/bin/lsof
Suppress command output:
Commond >/dev/null #输出到空文件
/dev/null >file #清空file里面的所有内容
To create a temporary file:
Mktemp
-T: Create a temporary file under/tmp
-D: Create a temp directory
file= ' Mktemp–t temp. XXXXXX '
Message logging:
Tee: Prints the message in the file specified by stdout and tee
Tee filename
-a writes the filename in append mode
16. Script Control
Stop signal: CTRL + C
Stop signal: CTRL + Z
Signal capture: Trap commands signals
Trap "echo Hello World" SIGINT SIGTERM
Some commands are executed before the script exits:
Trap "Echo Exit" exit
Removal Capture: trap-exit
Run the script without using the console: Nohup./xx.sh &
View Jobs: Jobs
Parameters |
Describe |
-L |
List PID and job numbers for a process |
-N |
Only jobs that have changed state since the last shell notification were listed |
-P |
List only the PID of the job |
-R |
List only jobs that are running |
-S |
List only jobs that are stopped |
Table 16.1 Job Command parameters
Restart stopped jobs: BG Job number FG Job number (running in the background)
17. Array variables and functions
The delivery of the array:
myarray= (0 1 2 3 4 5 6)
Farray ${myarray[*]}
The function receives an array:
function Farray
{
Local NewArray
newarray= (' echo ' [email protected] ')
echo "New array is: ${newarray[*]}"
echo "The third number is: ${newarray[2]}"
}
18. Create a library
. Pathname Loading Library
or source pathname #pathname为库的名称含路径如:./mylib
19. Add Color
eg:^[[33m
^[is a combination of CTRL + V followed by a [need to add yourself
20. SED programming
Replacement: S/pattern/replacdment/flags
Flags
-Number: Indicates the mode of new text substitution
-G: Indicates that all characters of existing text are replaced with new text
-P: The line in the printed text that contains the replacement string is often used with the-N (no sed editor output)
-W File: Writes the result of the substitution to a file
eg:sed ' S/TEST/TRIAL/2 ' data #替换每行的第二个test
Use Address:
eg:sed ' 2,3s/dog/cat/' file #只替换2, 3 rows of dog
Sed ' 2, $s/dog/cat/' file #从第2行开始替换知道末尾
Delete Row: D (delete from output only, original file unchanged)
Eg:sed ' 2d ' data #删除第2行
Inserting and attaching text:
Sed ' [address]command\
New Line '
Command
I: Add a new row before the specified line
A: Add a new line after the specified line # $a \ Add at the end of the file
Eg:echo "Testing" | Sed ' i\
>this is a test '
Change row: C
Eg:sed ' 3c\
>this is a changed line ' data
Replace command sed ' y/inchars/outchars/'
eg:sed ' y/123/789/' data #1->7 2->8 3->9
Write file: [address]w filename
Read file: [address]r filename
21. Regular Expressions
Special characters in regular expressions:. *[]^${}\+| () #作为文本字符需要转义 \
Locator:
^[address] #address只能出现在文本开头的位置
[Address]$ #address只能出现在文本结尾的位置
To find a row of data that contains only a specific text pattern:
Sed–n '/^this is a test$/p ' data
Remove empty line: sed '/^$/d ' data
Dot character:. #通配一个字符 eg:sed–n '/.at/p ' data # XAT
Character class: Echo "Yes" | Sed–n '/[yy]es/p ' #yes或Yes匹配
echo "Yes" | Sed–n '/[yy][ee][ss]/p ' #yes/yes/yes ...
Negative character class: Sed–n '/[^ch]at/p ' data #xat in addition to cat and hat
Use range: [0-9] #匹配0-9 value
Special characters
*: Can not appear or appear multiple times
?: Can not appear or appear once
+: appears at least once
{}:--->
M: happens to happen m times
M,n: Appears at least m times up to N times
|: Or, enclosed in ()
(| |-|) : Either there is either a space or a-number
( |-|) : Space OR-no
Note: Gawk does not recognize the regular expression and must be prefixed with the--re-interval command
Shell Script Programming Notes