1. Input and Output Redirection#
Review 1 Input and Output Redirection
Input
read -p "Please enter: " a -p prompt a assigned to a
read -s password hidden
Output
echo
# echo -e "abc\t abc" escape character output
abc abc
# echo "abc\t abc"
abc\t abc
echo -n no newline
echo -e escape character output
2. Two Special Files#
Knowledge Point 2 Two Special Files
Two special files
·/dev/null
: filters standard error messages
·/dev/zero
: used to create files of specified length
/dev/null
: black hole file, does not save or output information, just throws it into the black hole file
/dev/zero
: used to generate files of specified size, generates a bunch of 0s
Example: /dev/zero
: used to generate files of specified size, generates a bunch of 0s
/dev/zero
is generally used to generate files of specified size for testing purposes
dd is a backup command that can also produce a file of specified size
if input file
of output file
bs size of the output data unit
count number of output data units
Example: _______________________________________________________
[root@sanchuang-linux dev]# dd if=/dev/zero of=/tmp/test.dd bs=1M count=5
5+0 records in
5+0 records out
5242880 bytes (5.2 MB, 5.0 MiB) copied, 0.00196718 s, 2.7 GB/s
[root@sanchuang-linux dev]# du -sh /tmp/test.dd
5.0M /tmp/test.dd
if where to input, of where to output this file, bs data unit size, count data unit number
3. Here Document#
Knowledge Point 3 Here Document
here document the document is here
<<
Generate a document with specified content.
Used in simple scripts
Example:
-----------------------------------------------------------
[root@sanchuang-linux chenpeng]# cat >here_test.txt <<EOF
> nihao
> sanchuang
> huanying
> world............
> x y z
\> EOF
[root@sanchuang-linux chenpeng]# cat here_test.txt
nihao
sanchuang
huanying
world............
x y z
Knowledge Point 3.2 EOF is the document end marker can be defined by oneself (end of file)
Example:
------------------------------------------------------
[root@sanchuang-linux chenpeng]# cat >here_test <<XYZ
> nihao
> hello world
> XYZ
[root@sanchuang-linux chenpeng]# cat here_test
nihao
hello world
4. Tee Command#
Knowledge Point 4 Tee Command
tee command outputs to the screen and also redirects to a file
Example:
----------------------------------
[root@sanchuang-linux chenpeng]# echo "aa" >test_aa.txt #(Note: by default does not output to the screen)
[root@sanchuang-linux chenpeng]# cat test_aa.txt
aa
[root@sanchuang-linux chenpeng]# echo "bb" |tee test_bb.txt #
(Note: screen + file)
bb
[root@sanchuang-linux chenpeng]# cat test_bb.txt
bb
5. Clear File Content#
Knowledge Point 5 Clear File Content
[root@sanchuang-linux chenpeng]# >test_bb.txt
[root@sanchuang-linux chenpeng]# echo > test_bb.txt
#(Note: has newline)
[root@sanchuang-linux chenpeng]# cat test_bb.txt
[root@sanchuang-linux chenpeng]# echo -n > test_bb.txt
[root@sanchuang-linux chenpeng]# cat test_bb.txt
[root@sanchuang-linux chenpeng]# :>test_bb.txt
[root@sanchuang-linux chenpeng]# cat test_bb.txt
Knowledge Point 6 Echo
echo
Displays a piece of text or specified content on the screen
Outputs variables, outputs specified content
-e option escape character output
-n option no newline
6. Introduction to SHELL#
Introduction to shell
Shell is a program written in C language, it is the bridge for users to use Linux
Shell scripts implement automation, repetitive operations are completed by writing scripts, reducing human errors
Shell Variables#
Shell Variables
-
Local variables defined in scripts or commands
-
Environment variables that can be accessed by programs started by the shell env, echo $PATH
-
Shell variables
Example: Environment Variables
------------------------------------------
[root@sanchuang-linux chenpeng]# which ls
alias ls='ls --color=auto'
/usr/bin/ls #(Note: Environment variable)
[root@sanchuang-linux chenpeng]# echo $PATH #(Note: Environment variable)
/lianxi/sc:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin:/root/bin:/usr/local/nginx5/sbin:/root/bin
Example 2: Local Variables
-------------------------------------------
a=1
echo $a
echo ${a}
Knowledge Point 8.2 Variable Naming Rules
Variable Naming Rules:
Composed of numbers, letters, and underscores, cannot start with a number
Cannot use keywords in bash
To use a defined variable, you need to add a $ symbol in front of it
Example:
--------------------------------------------
[root@sanchuang-linux chenpeng]# echo $PATH #(Note: Environment variable)
/lianxi/sc:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin:/root/bin:/usr/local/nginx5/sbin:/root/bin
Shell Receives Parameters#
Knowledge Point 9 Shell Receives Parameters
Shell receives
Positional Variables: $1 - $9, representing the 1st - 9th parameters in the parameter list
Can be reused (i.e., the script can have two $1s)
Predefined Variables, some variables reserved by the system:
$0 Current process or script name
$! PID of the last background process
$? Return value of the last command
$* Represents all parameter contents
$$ Represents the current process PID
$# Represents the number of parameters
$@ Represents all parameters (extracted one by one)
# perror 1
Check the return value of the command and see the specific meaning of the return value
$? A return value of 0 indicates normal execution
Any non-zero value indicates a runtime error
Example: __________________________________
[root@mysql-binary shell_test]# echo $?
1
[root@mysql-binary shell_test]# perror 1
OS error code 1: Operation not permitted
#!/bin/bash It is best to add this line at the beginning of the script, specifying which interpreter to use for execution
Reason: In Unix-like operating systems, the default bash may vary for each operating system such as Ubuntu, Debian, CentOS
Example 1: Positional Variables $1, $2
__________________________________
[root@sanchuang-linux shell_test]# cat canshu.sh
#!/bin/bash
echo "########This is $1########" #(Note: Positional variable)
echo "$1" #(Note: Positional variable)
echo "########This is $2########" #(Note: Positional variable)
echo "$2" #(Note: Positional variable)
[root@sanchuang-linux shell_test]# sh canshu.sh "hello" "world" #
(Note: passed 2 parameters)
########This is hello######## #(Note: Parameter 1)
hello
########This is world######## #(Note: Parameter 2)
world
Example 2: Predefined Variable $0
__________________________________________________________
[root@sanchuang-linux shell_test]# echo $0 #(Note: $0 Current process or script name)
-bash
[root@sanchuang-linux shell_test]# sh canshu.sh "hello" "world"
########This is hello########
hello
########This is world########
world
canshu.sh #(Note: $0 Current process or script name)
[root@sanchuang-linux shell_test]# cat canshu.sh
#!/bin/bash
echo "########This is $1########"
echo "$1"
echo "########This is $2########"
echo "$2"
echo "$0"
Example 3: Predefined Variables $* $# $@
_____________________
[root@sanchuang-linux shell_test]# vim canshu.sh
#!/bin/bash
echo "########This is $1########"
echo "$1"
echo "########This is $2########"
echo "$2"
echo "$0"
echo "This is all:$*" #(Note: $* represents all parameter contents)
echo "Number of parameters: $#" #(Note: $# represents the number of parameters)
echo "This is @:$@" #(Note: $@ represents all parameters (extracted one by one))
──────────────────────────────────────────────
[root@sanchuang-linux shell_test]# sh canshu.sh hello world 2020 #(Note: 3 parameters)
########This is hello########
hello
########This is world########
world
canshu.sh
This is all:hello world 2020
Number of parameters:3
This is @:hello world 2020
Knowledge Point 10 Python Receives Parameters sys Module
In Python
The argv attribute in the sys module. The parameters passed after python are a list
, then get the first and second
[root@sanchuang-linux ~]# vim canshu.py
import sys
print(sys.argv[1],sys.argv[2]) #(Note: 1 receives parameter 1, 2 receives parameter 2)
print(sys.argv[0]) #(Note: 0 is the filename)
----------------------------------------------------------------------
[root@sanchuang-linux ~]# python3 canshu.py "hello" "world"
hello world
canshu.py
Data Types#
Knowledge Point 11 Data Types
Common numbers, strings, arrays in shell
String definitions can use single quotes, double quotes, or no quotes
Example: String Definition__________________
[root@sanchuang-linux ~]# echo abc
abc
[root@sanchuang-linux ~]# a=b
[root@sanchuang-linux ~]# echo $a
b
[root@sanchuang-linux ~]# a="b"
[root@sanchuang-linux ~]# echo $a
b
[root@sanchuang-linux ~]# a='b'
[root@sanchuang-linux ~]# echo $a
b
Example: Number Definition_________________
[root@sanchuang-linux ~]# a=1
[root@sanchuang-linux ~]# a=2
Difference Between Quotes#
Knowledge Point 12 Difference Between Quotes: Double quotes can recognize variables, single quotes cannot recognize variables
Difference in quotes: Double quotes can recognize variables, single quotes cannot
[root@sanchuang-linux ~]# head -n1 /etc/passwd #(Note: output the first line of passwd)
root:x:0:0:root:/root:/bin/bash
[root@sanchuang-linux ~]# cat /etc/passwd |head -n1 #(Note: not recommended to use this 2 commands)
root:x:0:0:root:/root:/bin/bash
#!/bin/bash
# String Operations
line=`head -n1 /etc/passwd` #(Note: using backticks ``)(Note: save command output in line)
echo $line
---------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# bash test2.sh
root:x:0:0:root:/root:/bin/bash
Example: Double quotes can recognize variables, single quotes cannot_____________________________
echo "The string is: $line"
The string is: root:x:0:0:root:/root:/bin/bash
------------------------------------------
echo 'The string is: $line'
The string is: $line
String Operations#
Knowledge Point 13 String Operations
Substring
Extract the first 4 characters: echo ${line:0:4}
Extract the last 9 characters echo ${line:0-9}
Extract 4 characters starting from the ninth last character echo ${line:0-9:4}
Extract the last character from left to right: after the character echo ${line##*:}
Extract the first character from left to right echo ${line#*:}
Extract the last character from right to left: after the character echo ${line%%:*}
Extract the first character from right to left echo ${line%:*}
String length echo ${#line}
Example: String Operations_______________________________
# String Operations
[root@sanchuang-linux chenpeng]# vim test2.sh
line=`head -n1 /etc/passwd`
echo $line #(Note: root:x:0:0:root:/root:/bin/bash)
echo "The string is: $line" #(Note: The string is: root:x:0:0:root:/root:/bin/bash)
echo 'The string is: $line' #(Note: The string is: $line)
echo "Extract the first 4 characters:"
echo ${line:0:4} #(Note: root)
echo "Extract the last 9 characters"
echo ${line:0-9} #(Note: /bin/bash)
echo "Extract 4 characters starting from the ninth last character"
echo ${line:0-9:4} #(Note: /bin)
echo "Extract the last character from left to right: after the character"
echo ${line##*:} #(Note: /bin/bash)
echo "Extract the first character from left to right"
echo ${line#*:} #(Note: x:0:0:root:/root:/bin/bash)
echo "Extract the last character from right to left: after the character"
echo ${line%%:*} #(Note: root)
echo "Extract the first character from right to left"
echo ${line%:*} #(Note: root:x:0:0:root:/root)
echo "String length"
echo ${#line} #(Note: 31)
-----------------------------------------------
[root@sanchuang-linux chenpeng]# bash test2.sh
root:x:0:0:root:/root:/bin/bash
The string is: root:x:0:0:root:/root:/bin/bash
The string is: $line
Extract the first 4 characters:
root
Extract the last 9 characters
/bin/bash
Extract 4 characters starting from the ninth last character
/bin
Extract the last character from left to right: after the character
/bin/bash
Extract the first character from left to right
x:0:0:root:/root:/bin/bash
Extract the last character from right to left: after the character
root
Extract the first character from right to left
root:x:0:0:root:/root
String length
31
Exercise 13 Extract Baidu URL
line="http://www.baidu.com/login"
# Extract: login
echo ${line:0-5} #(Note: take the last 5 characters)
echo ${line##*/} #(Note: from left to right the last content after /)
# Extract: www.baidu.com/login
echo ${line##*//}
# Extract: http://www.baidu.com
echo ${line%/*}
# Extract: http:
echo ${line%%/*}
Numerical Operations and Comparisons#
Knowledge Point 14 Numerical Operations and Comparisons
Numerical operations:
First type: $(( expression ))
Second type: $[ expression ]
Third type: expr expression
Note that there should be spaces
around the expression operators
Example: ↓↓↓↓↓↓↓↓↓↓↓↓↓↓
[root@sanchuang-linux ~]# a=10
[root@sanchuang-linux ~]# b=20
[root@sanchuang-linux ~]# $(($a + $b))
-bash: 30: command not found
[root@sanchuang-linux ~]# echo $(($a + $b))
30
[root@sanchuang-linux ~]# echo $[ $a +$b ]
30
[root@sanchuang-linux ~]# expr $a + $b
30
[root@sanchuang-linux ~]# expr $a+$b
10+20
Shell Structure Statements, Loops, and Conditions#
Knowledge Point 15 Shell Structure Statements, Loops, and Conditions
Knowledge Point 15.1 For Loop
For Loop
Syntax 1: ↓↓↓↓↓↓↓↓
-----------------------
for variable in value1 value2
do
execute loop statements
done
=======================================
Syntax 2: ↓↓↓↓↓↓↓↓
---------------------------------------
# for ((i=0;i<3;i++))
for ((initialize variable; condition to end loop; operation))
do
execute loop statements
done
Knowledge Point 15.2 While Loop
While Loop
Syntax 1: ↓↓↓↓↓↓
---------------------------------------
while read line
do
execute loop statements
done
=======================================
Syntax 2 ↓↓↓↓↓↓↓↓↓↓
---------------------------------------
while [condition (optional)]:
do
execute loop statements
done
=======================================
Note: also supports break, continue
Knowledge Point 15 Conditions
Knowledge Point 15.3 If Statement
If Statement
Syntax 1: ↓↓↓↓↓↓
-------------------------
if condition
then
execute statements
fi
=========================
Syntax 2: ↓↓↓↓↓↓
if condition
then
execute statements
else
execute statements
fi
==========================
Syntax 3: ↓↓↓↓↓↓↓
----------------------
if [ command ];then
execute statements that meet the condition
elif [ command ];then
execute statements that meet the condition
else
execute statements that meet the condition
fi
Knowledge Point 15.4 Case Statement
Case Statement
Syntax: ↓↓↓↓↓↓________________
case $variable in
condition1)
execute statement one
;;
condition2)
execute statement two
;;
*)
esac
Exercise 16
Write a shell script
Receive two numbers input by the user, then choose what calculation to perform on the two numbers, and output the result
Implement menu selection
================
-
add Addition
-
sub Subtraction
-
mul Multiplication
-
exit Exit
================
Note: Use case for menu selection, use case for service restart script
Example: ↓↓↓↓↓↓↓↓↓_________________________
[root@sanchuang-linux chenpeng]# vim num_test.sh
#!/bin/bash
read -p "Please enter the first number: " num1
read -p "Please enter the second number: " num2
echo "================"
echo "1.add Addition"
echo "2.sub Subtraction"
echo "3.mul Multiplication"
echo "4.exit Exit"
echo "================"
read -p "Please enter your choice: " options
case $options in
1)
echo "The sum of the two numbers is: $(($num1 + $num2))"
;;
2)
echo "The difference of the two numbers is: $(($num1 - $num2))"
;;
3)
echo "The product of the two numbers is: $(($num1 * $num2))"
;;
4)
echo "Exiting!"
exit
esac
-------------------------------------------------------------------------------------------
Make it into function form
add(){
echo "The sum of the two numbers is: $(($num1 + $num2))"
}
case $options in
1)
add #(Note: call when needed)
;;
2)…………………………
/etc/init.d Service Startup Script#
Knowledge Point 17 /etc/init.d Service Startup Script
/etc/init.d/ contains service startup scripts
[root@sanchuang-linux chenpeng]# cd /etc/init.d/
[root@sanchuang-linux init.d]# ls
functions README
Example: Service restart script using case ↓↓↓↓↓↓__________________
case $mode in
start)
start
;;
stop)
stop (using kill command)
;;
restart)
stop
start
;;
reload)
reload configuration (using kill -HUP)
;;
esac
Kill#
Knowledge Point 18 Kill
Kill is used to terminate running programs or jobs
Kill can send specified information to the program
# kill -l can view kill signals (kill -L (lowercase))
# kill -0 is used to check if a process exists, when the process does not exist, kill -0 will report an error
# kill -1 pid reload process (commonly used)
# kill -HUP pid and kill -1 pid are the same
# kill -1 pid or kill -HUP pid both indicate reloading this file
# kill -9 force kill
# kill -15 normally stop a process
Kill without a signal defaults to signal 15
Other signals, except signal 9, can be refused by the process!
Note: Reloading is equivalent to loading the latest configuration while the service is still running (connections will not be interrupted)
Restarting will interrupt the service
Example: ↓↓↓↓↓↓↓↓↓↓____________
[root@sanchuang-linux ~]# kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
…………………………
63) SIGRTMAX-1 64) SIGRTMAX
Shell Programming If Judgment#
Knowledge Point 19 Shell Programming If Judgment
If Judgment
Example: ↓↓↓↓↓↓____________________________________________________________
[root@sanchuang-linux ~]# if id wenyao; then echo "ok"; else echo "error"; fi
id: “wenyao”: no such user
error
--------------------------------------------------------
Equivalent to: ↓↓↓↓↓↓________________________________________________
if id wenyao;
then
echo "ok";
else
echo "error";
fi
[ ]#
Knowledge Point 20 [ ]
[ ] indicates condition testing
Note that spaces are important here. There must be spaces after '[' and before ']'.
Common Judgments:
[ -d FILE ] If FILE exists and is a directory, it returns true.
[ -f FILE ] If FILE exists and is a regular file, it returns true.
[ -e **** ] Check if file/folder exists
String Judgments:
[ -z STRING ] If the length of STRING is zero, it returns true, that is, empty is true
[ -n STRING ] If the length of STRING is non-zero, it returns true, that is, non-empty is true
[ STRING1 ] If the string is not empty, it returns true, similar to -n
[ STRING1 == STRING2 ] If the two strings are the same, it returns true
[ STRING1 != STRING2 ] If the two strings are different, it returns true
[ STRING1 < STRING2 ] If "STRING1" is lexicographically before "STRING2", it returns true.
[ STRING1 > STRING2 ] If "STRING1" is lexicographically after "STRING2", it returns true.
Numerical Judgments
[ INT1 -eq INT2 ] If INT1 and INT2 are equal, it returns true, =
[ INT1 -ne INT2 ] If INT1 and INT2 are not equal, it returns true, <>
[ INT1 -gt INT2 ] If INT1 is greater than INT2, it returns true, >
[ INT1 -ge INT2 ] If INT1 is greater than or equal to INT2, it returns true, >=
[ INT1 -lt INT2 ] If INT1 is less than INT2, it returns true, <
[ INT1 -le INT2 ] If INT1 is less than or equal to INT2, it returns true, <=
Logical Judgments
[ ! EXPR ] Logical NOT, if EXPR is false, it returns true.
[ EXPR1 -a EXPR2 ] Logical AND, if EXPR1 and EXPR2 are both true, it returns true.
[ EXPR1 -o EXPR2 ] Logical OR, if EXPR1 or EXPR2 is true, it returns true.
[ ] || [ ] Use OR to combine two conditions
[ ] && [ ] Use AND to combine two conditions
Example: ↓↓↓↓↓↓↓↓↓↓↓↓↓↓
[root@sanchuang-linux ~]# a=10
[root@sanchuang-linux ~]# b=20
[root@sanchuang-linux ~]# if [ $a -gt $b ];then echo "a>b";else echo "a<b";fi #(Note: correct)
a<b
[root@sanchuang-linux ~]# if [ $a > $b ];then echo "a>b";else echo "a<b";fi #(Note: error)
a>b (Note: using two brackets does not cause an error)
[root@sanchuang-linux ~]# if [[ $a > $b ]];then echo "a>b";else echo "a<b";fi #(Note: correct)
a<b
[root@sanchuang-linux ~]# if [ $a -gt $b ] && [ $a -ne 20 ];then echo "Output a>b";else echo "Output a<b";fi
Output a<b
Exercise 21
Check if file a exists in the current directory, if not, create it
If it exists, output that the file already exists
Example: ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
Writing 1:
if [ -f a.txt ];
then echo "File exists"
else
touch a.txt
fi
-------------------------------------------------
Writing 2: Recommended (similar to Python's if ternary operator)
[ -f a.txt ] && echo "File already exists" || touch a.txt
Example 2:
Write a script to implement the following functions
==============
-
Add user and set password
-
Delete user
-
View user
-
Exit
==============
If the input is not 1-4, give a prompt and reminder, and if not input exit, it can loop to add.
Press 1 to add a user and set the password useradd passwd
Press 2 to delete a user userdel -r
Press 3 to view user id
Press 4 to exit exit
&& ||#
Knowledge Point 22 Similar to Python's if ternary operator
Use && || to implement
·cmd1 && cmd2 If cmd1 executes successfully or is true, then execute cmd2
·cmd1 || cmd2 If cmd1 fails to execute or is false, then execute cmd2
·cmd1 && cmd2 || cmd3 If cmd1 executes successfully, then execute cmd2, if not, execute cmd3
Example: Previous Exercise ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
[ -f a.txt ] && echo "File already exists" || touch a.txt
[[ -f a.txt ]] && echo "File already exists" || touch a.txt #(Note: recommended to use two brackets)
Example:
-------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# a=10
[root@sanchuang-linux ~]# b=20
[root@sanchuang-linux ~]# [ $a -gt $b ] && echo "Output a>b"
[root@sanchuang-linux ~]# [ $a -gt $b ] || echo "Output a<b"
Output a<b
[root@sanchuang-linux ~]# [ $a -gt $b ] && echo "Output a>b" || echo "Output a<b"
Output a<b
[] 、[[]]、 (()) (Judgment Methods)#
Knowledge Point 23 [] 、[[]]、 (()) (Judgment Methods)
[ ] will do word splitting
[ ] Many expressions are not well supported, it is recommended to use [[ ]] for judgment (two brackets)
Summary:
· It is recommended to use
[[ ]]for comparison operations and judgments
· Use
[[ ]] for strings (recommended)** **
· Use`(( )) for numerical comparisons
Conclusion: It is recommended to use [[ ]] for comparison operations and judgments
Example 1: When judging if
-------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# name="wen yao"
[root@sanchuang-linux chenpeng]# [ $name == "wen yao" ] && echo "ok" || echo "error"
-bash: [: too many arguments #(Note: automatically does word splitting)
error
[root@sanchuang-linux chenpeng]# [[ $name == "wen yao" ]] && echo "ok" || echo "error"
ok #(Note: recommended to use two brackets)
[root@sanchuang-linux chenpeng]# [ "$name" == "wen yao" ] && echo "ok" || echo "error"
ok #(Note: using quotes to connect together indicates a whole)
============================================================================================
Example 2: Numerical Comparison
-------------------------------------------------------------------------------------------
[root@mysql-binary shell_test]# echo $a
10
[root@mysql-binary shell_test]# echo $b
20
[root@mysql-binary shell_test]# [[ $a > $b ]] && echo "ok" || echo "error"
error
[root@mysql-binary shell_test]# [ $a > $b ] && echo "ok" || echo "error"
ok #(Note: error)
[root@mysql-binary shell_test]# (( $a == $b )) && echo "ok" || echo "error"
error
Example:
--------------------------------------------------------------------------------------------
[root@mysql-binary shell_test]# a=10
[root@mysql-binary shell_test]# b=20
[root@mysql-binary shell_test]# [[ $a -eq $b ]] && echo "ok" || echo "eroor"
eroor
[root@mysql-binary shell_test]# (( $a -eq $b )) && echo "ok" || echo "eroor"
-bash: ((: 10 -eq 20 : syntax error in expression (error symbol is "20 ")
Eroor
-------------------------------------------------------------------------------
[root@mysql-binary shell_test]# c=102
[root@mysql-binary shell_test]# b=20
[root@mysql-binary shell_test]# [[ $c > $b ]] && echo "ok" || echo "eroor"
eroor
[root@mysql-binary shell_test]# (( $c > $b )) && echo "ok" || echo "eroor"
ok
Example 3: Two Ways of Writing If Condition Judgments
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# a=10
[root@sanchuang-linux ~]# b=20
[root@sanchuang-linux ~]# if [[ $a > $b ]]; then echo "ok"; else echo "error"; fi
error
[root@sanchuang-linux ~]# [[ $a > $b ]] && echo "ok" || echo "error"
error
Example: String Comparison (( )) can also be used
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# a=abc
[root@sanchuang-linux ~]# b=abc1
[root@sanchuang-linux ~]# (( $a > $b )) && echo "ok" || echo "error"
error
[root@sanchuang-linux ~]# a=abc
[root@sanchuang-linux ~]# b=bac1
[root@sanchuang-linux ~]# (( $a > $b )) && echo "ok" || echo "error"
error
[root@sanchuang-linux ~]# a=abc
[root@sanchuang-linux ~]# b=abc
[root@sanchuang-linux ~]# (( $a == $b )) && echo "ok" || echo "error"
ok
Conclusion: It is recommended to use [[ ]] for comparison operations and judgments
Shell Functions Definition#
Knowledge Point 24 Shell Functions Definition
Example:
add() {
echo "The sum of the two numbers is: $(( $num1 + $num2 ))" #(Note: content of operations inside the function)
}
------------------------------------------------
Call when needed add
case $options in
1)
add
;;
2)……………………
--------------------------------------------------------------------------------------------
add(){
echo "The sum of the two numbers is: $(($num1 + $num2))"
}
case $options in
1)
add #(Note: call when needed)
;;
2)…………………………
Judgment Methods [] [[]] (()) test#
Knowledge Point 25 Judgment Methods [] [[]] (()) test
-
(( )) judges numbers > < == !=
-
[[ ]] judges strings or -eq -ne -gt -lt for judging numbers
-
Some syntax [ ] are not supported, it is recommended to use [[ ]]
-
test (test) judgment, equivalent to one bracket
Example: test
---------------------------------------------------------------------
[root@sanchuang-linux ~]# a=123
[root@sanchuang-linux ~]# b=123
[root@sanchuang-linux ~]# test a==b && echo ok
ok
[root@sanchuang-linux ~]# test a==b && echo ok || echo error
ok