1, Shell script
use #/ bin/bash or #/ bin/sh definition
#!/bin/bash echo "Alian love java"
2, Shell variable
- Naming can only use English letters, numbers and underscores. The first character cannot start with a number
- There must be no space between the variable name and the equal sign. You can use the underscore ()
- Punctuation cannot be used
- Keywords in bash cannot be used (you can use the help command to view reserved keywords)
the following are legal variable definitions
#!/bin/bash projectName="pay" project_name="query" _project_name="notice"
2.2. Use variables
use a defined variable, as long as the dollar sign ($) is added in front of the variable name, such as:
#!/bin/bash projectName="pay" echo $projectName echo ${projectName}
Both methods are OK, but the second method is more used when string splicing variables, and will not report errors
2.3 read only variable
variables with readonly are read-only variables and cannot be changed
#!/bin/bash readonly systemName="Linux" systemName="ubuntu"
You will be prompted: systemName: read only variable
2.4. Delete variable
use the unset command to delete variables
#!/bin/bash tempStr="abcdef" unset tempStr echo $tempStr
then the variable result will be empty
3, Shell string
3.1 single quotation mark
- Any character in the single quotation mark will be output as it is, and the variable in the single quotation mark string is invalid
- A single single quotation mark cannot appear in a single quotation mark string (nor after using the escape character for single quotation marks), but it can appear in pairs and be used as string splicing
#!/bin/bash str='this is a simple string' echo $str
3.2 double quotation marks
- There can be variables in double quotation marks
- Escape characters can appear in double quotation marks
#!/bin/bash operating_system="linux" str="Hello, operating system is \"$system_name\"! \n" echo -e $str
3.3 splicing string (double quotation marks)
there can be variables in double quotation marks, and escape characters can also appear in double quotation marks
#!/bin/bash username="alian" greeting="Hello $username" echo $greeting
Operation results:
Hello alian
3.4 splicing string (single quotation mark)
any character in single quotation marks will be output as is, and the variable in single quotation marks string is invalid
#!/bin/bash username='alian' greeting='Hello $username' echo $greeting
Operation results:
Hello $username
3.five. Get string length
#!/bin/bash tempstr="abcd" echo "Length of string: ${#tempstr}"
Operation results:
Length of string: 4
3.6. Extract substring
The subscript starts at 0
#!/bin/bash string="Alian is learning java" echo ${string:1:5} string="runoob is a great site" echo `expr index "$string" io`
Operation results:
lian
3.7. Find substring
find the position of the character i or o (the position starts from 1, and the letter that appears first is calculated)
#!/bin/bash string="Alian is learning java" echo `expr index "$string" ia`
Operation results:
3
4, Shell array
4.1 array definition and value
use parentheses to represent the array, and the array elements are separated by "space symbol", as follows:
array name = (value 1, value 2... Value n)
#!/bin/bash fruits=("Apple" "Banana" "Orange" "kiwifruit") #Value by subscript, starting from 0 echo ${fruits[2]} # Use the @ symbol or * symbol to get all the elements in the array, for example: echo ${fruits[@]} echo ${fruits[*]}
Operation results:
Orange Apple Banana Orange kiwifruit Apple Banana Orange kiwifruit
4.2. Get the length of the array
the method of obtaining the length of an array is similar to that of a string
${# array name [*]} or ${# array name [@]}
#!/bin/bash fruits=("Apple" "Banana" "Orange" "kiwifruit") #Two ways to get the length of an array echo "Method 1: array length: ${#fruits[*]}" echo "Method 2: array length: ${#fruits[@]}"
Operation results:
Method 1: array length: 4 Mode 2: array length: 4
5, Shell comments
5.1. Single line notes
lines beginning with # are comments and will be ignored by the interpreter.
#!/bin/bash #alian is summarizing the basics of Shell programming #If you have any questions, you can contact me through the blog #Blog address: https://blog.csdn.net/Alian_1223 echo "I'll be waiting for you"
Operation results:
I'll be waiting for you
5.2 multi line notes
of course, you can set multi line comments by adding a # number to each line. Here we will talk about other ways
#!/bin/bash echo "eof Note content in format" :<<EOF eof Format Note content eof Format Note content eof Note content format EOF echo "Exclamation mark format comment content" :<<! Exclamation mark format comment content Exclamation mark format comment content Exclamation mark format comment content ! echo "Comment content in single quotation mark format" : ' Single quotation mark format comment content Single quotation mark format comment content Single quotation mark format comment content '
Operation results:
eof Note content in format Exclamation mark format comment content Comment content in single quotation mark format
Note that there is a space between colon and single quotation mark in the third way
6, Shell operator
- Arithmetic operator
- Relational operator
- Boolean operator
- Logical operator
- String operator
- File test operator
6.1 arithmetic operators
#!/bin/bash a=100 b=20 # addition val=`expr $a + $b` echo "a + b : $val" #subtraction val=`expr $a - $b` echo "a - b : $val" #Multiplication (pay attention to escape symbols) val=`expr $a \* $b` echo "a * b : $val" #division val=`expr $b / $a` echo "b / a : $val" #Seeking module val=`expr $b % $a` echo "b % a : $val" #Equality judgment if [ $a == $b ] then echo "a be equal to b" fi #Unequal judgment if [ $a != $b ] then echo "a Not equal to b" fi
Operation results:
a + b : 120 a - b : 80 a * b : 2000 b / a : 0 b % a : 20 a Not equal to b
It should be noted that the conditional expression should be placed between square brackets with spaces. For example: [$a==$b] is wrong and must be written as [$a==$b]
6.2. Relational operators
operator | English whole journey | meaning |
---|---|---|
-eq | equal | be equal to |
-ne | not equal | Not equal to |
-gt | greater than | greater than |
-lt | less than | less than |
-ge | greater than or equal | Greater than or equal to |
-le | less than or equal | Less than or equal to |
#!/bin/bash a=100 b=20 if [ $a -eq $b ] then echo "$a -eq $b : a be equal to b" else echo "$a -eq $b: a Not equal to b" fi if [ $a -ne $b ] then echo "$a -ne $b: a Not equal to b" else echo "$a -ne $b : a be equal to b" fi if [ $a -gt $b ] then echo "$a -gt $b: a greater than b" else echo "$a -gt $b: a Not greater than b" fi if [ $a -lt $b ] then echo "$a -lt $b: a less than b" else echo "$a -lt $b: a Not less than b" fi if [ $a -ge $b ] then echo "$a -ge $b: a Greater than or equal to b" else echo "$a -ge $b: a less than b" fi if [ $a -le $b ] then echo "$a -le $b: a Less than or equal to b" else echo "$a -le $b: a greater than b" fi
Operation results:
100 -eq 20: a Not equal to b 100 -ne 20: a Not equal to b 100 -gt 20: a greater than b 100 -lt 20: a Not less than b 100 -ge 20: a Greater than or equal to b 100 -le 20: a greater than b
It should be noted that there are spaces in if, [, variable, relational operator, variable,] and do not omit them
6.3 Boolean operators
Symbol | English whole journey | meaning |
---|---|---|
! | not | Non operation |
-o | or | Or operation |
-a | and | And operation |
#!/bin/bash a=100 b=20 if [ $a != $b ] then echo "$a != $b : a Not equal to b" else echo "$a == $b: a be equal to b" fi #And operation if [ $a -lt $b -o $a -lt 200 ] then echo "$a -lt $b -o $a -lt 200: return true" else echo "$a -lt $b -o $a -lt 200: return false" fi #And operation if [ $a -gt $b -a $a -gt 200 ] then echo "$a -gt $b -a $a -gt 200: return true" else echo "$a -gt $b -a $a -gt 200: return false" fi
Operation results:
100 != 20 : a Not equal to b 100 -lt 20 -o 100 -lt 200: return true 100 -gt 20 -a 100 -gt 200: return false
6.4 logical operators
& & is logical and, |𞓜 is logical or
#!/bin/bash a=100 b=20 if [[ $a -gt fifty && $b -gt 50 ]] then echo "return true" else echo "return false" fi if [[ $a -gt 50 || $b -gt 50 ]] then echo "return true" else echo "return false" fi
Operation results:
return false return true
6.5. String operator
operator | meaning | use |
---|---|---|
= | Check whether two strings are equal, and return true if they are equal | [ $a = $b ] |
!= | Detect whether two strings are not equal, and return true if they are not equal | [ $a != $b ] |
-z | Check whether the string length is 0, and return true if it is 0 | [ -z $a ] |
-n | Check whether the string length is not 0, and return true if it is not 0 | [ -n "$a" ] |
$ | Check whether the string is empty. If not, return true | [ $a ] |
#!/bin/bash a="abcdefg" b="hijklmn" if [ $a = $b ] then echo "$a = $b Test for equality, return true" else echo "$a = $b Test for equality, return false" fi if [ $a != $b ] then echo "$a != $b Test whether it is not equal, return true" else echo "$a != $b Test whether it is not equal, return false" fi if [ -z $a ] then echo "-z $a Test whether it is 0 and return true" else echo "-z $a Test whether it is 0 and return false" fi if [ -n $a ] then echo "-n $a Test whether it is not returned for 0 true" else echo "-n $a Test whether it is not 0, return false" fi if [ $a ] then echo "$a Test whether it is empty, return true" else echo "$a Test whether it is empty, return false" fi
Operation results:
abcdefg = hijklmn Test for equality, return false abcdefg != hijklmn Test whether it is not equal, return true -z abcdefg Test whether it is 0 and return false -n abcdefg Test whether it is not returned for 0 true abcdefg Test whether it is empty, return true
6.6 document test operator
operator | meaning | use |
---|---|---|
-b file | Check whether the file is a block device file. If so, return true | [ -b $file ] |
-c file | Check whether the file is a character device file. If so, return true | [ -c $file ] |
-d file | Check whether the file is a directory. If so, return true | [ -d $file ] |
-f file | Check whether the file is an ordinary file (neither a directory nor a device file). If so, return true | [ -f $file ] |
-g file | Check whether the SGID bit is set in the file. If so, return true | [ -g $file ] |
-k file | Check whether the file has a sticky bit set. If so, return true | [ -k $file ] |
-p file | Check whether the file is a famous pipeline. If so, return true | [ -p $file ] |
-u file | Check whether the SUID bit is set in the file. If so, return true | [ -u $file ] |
-r file | Check whether the file is readable. If so, return true | [ -r $file ] |
-w file | Check whether the file is writable. If so, return true | [ -w $file ] |
-x file | Check whether the file is executable. If so, return true | [ -x $file ] |
-s file | Check whether the file is empty (whether the file size is greater than 0). If it is not empty, return true | [ -s $file ] |
-e file | Check whether files (including directories) exist. If so, return true | [ -e $file ] |
there are too many operators here, so I won't demonstrate them one by one. Just pick some commonly used ones
#!/bin/bash file="/home/shell/logic.sh" echo "file[$file]The properties are as follows:" if [ -r $file ] then echo "File readable" else echo "File unreadable" fi if [ -w $file ] then echo "File writable" else echo "The file is not writable" fi if [ -x $file ] then echo "File executable" else echo "The file is not executable" fi if [ -f $file ] then echo "The file is ordinary" else echo "The document is a special document" fi if [ -d $file ] then echo "The file is a directory" else echo "File is not a directory" fi if [ -s $file ] then echo "File is not empty" else echo "File is empty" fi if [ -e $file ] then echo "File exists" else echo "file does not exist" fi
Operation results:
file[/home/shell/logic.sh]The properties are as follows: File readable File writable File executable The file is ordinary File is not a directory File is not empty File exists
7, Shell echo command
Shell echo command is used for string output. Let's talk about several common commands
7.1. Display string
#!/bin/bash #Double quotes are not required echo study hard and make progress every day #With double quotation marks echo "study hard and make progress every day" #Use escape characters to display double quotes echo \"study hard and make progress every day\"
Operation results:
study hard and make progress every day study hard and make progress every day "study hard and make progress every day"
7.2 line feed and no line feed
#!/bin/bash #-n can output without line break echo -n "Hello ";echo "Shell" #Output wrap echo -e "I'll wrap: Echo output wrap \n" #Output does not wrap echo -e "I won't wrap: Echo output does not wrap \c" #Output next line echo "isn't it?"
Operation results:
Hello Shell I'll wrap: Echo output wrap I won't wrap: Echo output does not wrap isn't it?
7.3. Display results directed to file
#!/bin/bash echo "Test echo output to file" > echoToFile.txt
If it is an additional file, it changes from > to > >
#!/bin/bash echo "Test echo output to file" >> echoToFile.txt
7.4. Display command execution results
#!/bin/bash #Displays the current time echo `date` #Display network information echo "`ifconfig`"
Operation results:
2022 Wednesday, February 16, 2010:24:25 CST eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.26.163.146 netmask 255.255.240.0 broadcast 172.26.115.255 inet6 fe80::216:3eff:fe1c:c5e5 prefixlen 64 scopeid 0x20<link> ether 00:16:3e:1c:c5:e5 txqueuelen 1000 (Ethernet) RX packets 764979 bytes 149477332 (142.5 MiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 951246 bytes 182426261 (173.9 MiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> loop txqueuelen 1000 (Local Loopback) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
8, Shell printf command
#!/bin/bash printf "%-10s %-8s %6s %11s\n" Fruit unit price quantity total price printf "%-10s %-8s %-6d %1.2f\n" Apple 5.00 10 50.00 printf "%-10s %-8s %-6d %1.2f\n" Banana 3.00 5 15.00 printf "%-10s %-8s %-6d %1.2f\n" Cherry 50.00 2 100.00
Operation results:
Fruits Unit price quantity Total price Apple 5.00 10 50.00 Banana 3.00 5 15.00 Cherry 50.00 2 100.00
- %S% c% d% F are all format substitutes,% s outputs a string,% d integer output,% c outputs a character,% f outputs a real number and outputs it in decimal form.
- %-8s refers to a width of 8 characters (- left aligned, no right aligned)
- %1.2f refers to formatting as decimal, where. 2 refers to retaining 2 decimal places.
9, Shell test command
first, let's look at the meaning of the operators mentioned earlier, as follows:
operator | English whole journey | meaning |
---|---|---|
-eq | equal | be equal to |
-ne | not equal | Not equal to |
-gt | greater than | greater than |
-lt | less than | less than |
-ge | greater than or equal | Greater than or equal to |
-le | less than or equal | Less than or equal to |
9.1 digital test
#!/bin/bash a=100 b=20 if test $[a] -eq $[b] then echo "$a and $b equal!" else echo "$a and $b Unequal!" fi if test $[a] -gt $[b] then echo "$a greater than $b " else echo "$a less than $b" fi
Operation results:
100 And 20 are not equal! 100 Greater than 20
9.2 string test
Symbol | meaning |
---|---|
= | Equal to true |
!= | Equal is not true |
-z string | If the length of the string is zero, it is true |
-n string | True if the length of the string is not zero |
#!/bin/bash a="abcdefg" b="hijklmn" if test $a = $b then echo "$a and $b Two strings are equal" else echo "$a and $b The two strings are not equal!" fi if test -z $a then echo "$a The string length is zero" else echo "$a String length is not zero" fi
Operation results
abcdefg and hijklmn The two strings are not equal! abcdefg String length is not zero
9.3 document test
in fact, the file test operator has been discussed in section 6.6 of this article, so I won't say more. See the above for details.
10, Shell process control
process control can also be carried out in the Shell, such as condition judgment and circulation
10.1,if
in fact, we have seen a lot of if judgments before. Its grammatical structure is roughly as follows:
if condition then command fi
Define a string. If the string is not empty, splice another string, and then output the result
#!/bin/bash tempStr="Hello" if test -n $tempStr then tempStr="$tempStr, Shell" fi echo $tempStr
Operation results:
Hello, Shell
10.2,if else
The syntax structure of if else is as follows:
if condition then command1 else command2 fi
Define two numbers and judge whether they are equal
#!/bin/bash a=100 b=20 if test $a -eq $b then echo "$a and $b equal!" else echo "$a and $b Unequal!" fi
Operation results:
100 And 20 are not equal!
10.3,if else-if else
The syntax structure of if else if else is as follows:
if condition1 then command1 elif condition2 then command2 else commandN fi
#!/bin/bash a=100 b=20 if [ $a == $b ] then echo "$a be equal to $b" elif [ $a -gt $b ] then echo "$a greater than $b" else echo "$a less than $b" fi
Operation results:
100 Greater than 20
Note: else if is actually elif
10.4 for cycle
The syntax structure of for loop is as follows:
for var in item1 item2 ... itemN do command1 command2 ... commandN done
simple demonstration of a for loop
#!/bin/bash for num in 1 2 3 4 5 6 do echo "For loop value is: $num" done
Operation results:
For loop value is: 1 For loop value is: 2 For loop value is: 3 For loop value is: 4 For loop value is: 5 For loop value is: 6
10.5. while cycle
The syntax structure of while loop is as follows:
while condition do command done
#!/bin/bash maxcount=3 count=1 pwd="123456" while [ $count -le $maxcount ] do echo -n "The first ${count}Enter your password once:" read input if [ $pwd -eq $input ] then echo "The first ${count}The password entered is correct, and the login is successful" break fi echo "Wrong password ${count}second" if [ $count -gt $maxcount ] then echo "Maximum number of password errors:$maxcount" break fi count=`expr $count + 1` done
Operation results:
Enter your password for the first time: 123123 Wrong password, wrong input once Enter your password for the second time: 222222 Wrong password, wrong input twice Enter your password for the third time: 123456 The password entered for the third time is correct and the login is successful
10.6 infinite cycle
infinite loop means that the condition is always true. The syntax structure of infinite loop is as follows:
while true do command done
or
while : do command done
or
for (( ; ; ))
10.7,case ... esac
The syntax structure of case... esac loop is as follows:
case Mode value in Mode 1) command1 ;; Mode 2) command2 ;; esac
suppose you go to the lottery by selecting numbers
#!/bin/bash echo "Enter a number between 1 and 3" echo -n "The number you entered is:" read aNum case $aNum in "1") echo "Congratulations on winning 100 yuan!" ;; "2") echo "Congratulations on winning 200 yuan!" ;; "3") echo "Unfortunately, I didn't win the prize" ;; esac
Operation results:
Enter a number between 1 and 3 The number you entered is:2 Congratulations on winning 200 yuan! Enter a number between 1 and 3 The number you entered is:3 Unfortunately, I didn't win the prize
10.8,break
we write an infinite loop to demonstrate that the user enters a number within the specified range, otherwise exit the program.
#!/bin/bash while true do echo -n "Please enter a number from 1 to 100:" read num if [[ $num -lt 1 || $num -gt 100 ]] then echo "Sorry, the number you entered ${num}Not a number between 1 and 100" break fi echo "The number you entered is: $num" done
Operation results:
Please enter a number from 1 to 100: 1 The number you entered is: 1 Please enter the number from 1 to 99 The number you entered is: 99 Please enter a number from 1 to 100: 120 Sorry, the number 120 you entered is not in the middle of 1 to 100
It should be noted that if there are multiple nested loops, the break keyword is to jump out of the current loop, not the whole loop.
10.9,continue
We demonstrate the need for an even number of outputs between 1 and 10
#!/bin/bash for num in 1 2 3 4 5 6 7 8 9 10 do if [[ `expr $num % 2` != 0 ]] then continue fi echo "Even number obtained: ${num}" done
Operation results:
Even number obtained: 2 Even number obtained: 4 Even number obtained: 6 Even number obtained: 8 Even number obtained: 10
11, Shell pass parameters
11.1 basic usage
Let's start with a simple example
#!/bin/bash echo "Shell Transfer parameters" echo "Executed file name: $0" echo "The first parameter passed in is: $1" echo "The second parameter passed in is: $2" echo "The third parameter passed in is: $3"
We execute:
sh /home/shell/params.sh apple orange banana
Operation results:
Shell Transfer parameters Executed file name:/home/shell/params.sh The first parameter passed in is: apple The second parameter passed in is: orange The third parameter passed in is: banana
11.2 description of other parameters
parameter | explain |
---|---|
$# | Number of parameters passed to the script |
$* | A single string displays all parameters passed to the script |
$$ | The ID number of the current process that the script is running |
$! | ID number of the last process running in the background |
$@ | Same as $*, but use in quotation marks and return each parameter in quotation marks |
$- | Displays the current options used by the Shell, which has the same function as the set command |
$? | Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error |
Let's see the effect separately
#!/bin/bash echo "1,Number of parameters passed by executing script: $#" echo "2,Execute all parameters passed by the script(A single string): $*" echo "3,The current process in which the script is running ID(important): $$" echo "4,Of the last process running in the background ID number: $!" echo "5,Shell Current options used: $-" echo "6,Exit status of command: $?" echo "7,\$@use,Remember to use double quotation marks" for var in "$@" do echo $var done
Operation results:
1,Number of parameters passed by executing script: 3 2,Execute all parameters passed by the script(A single string): apple orange banana 3,The current process in which the script is running ID(important): 1338260 4,Of the last process running in the background ID number: 5,Shell Current options used: hB 6,Exit status of command: 0 7,$@use,Remember to use double quotation marks apple orange banana
12, Function
12.1. Simple use
In Shell, you can pass parameters to a function when you call it. Inside the function body, the value of the parameter is obtained in the form of $n. for example, $1 represents the first parameter, $2 represents the second parameter..., as shown in the following example:
#!/bin/bash testFuction(){ echo "Function call received" echo "The parameters passed in are: $*" echo "full name: $1" echo "Gender: $2" echo "Age: $3" } echo "-----Function call start-----" testFuction Alian Male 18 echo "-----End of function call-----"
Operation results:
-----Function call start----- Function call received The parameters passed in are: Alian Male 18 full name: Alian Gender: Male Age: 18 -----End of function call-----
12.2. Get the return value of the function
The return values of functions are generally 0 and 1, indicating success and failure
#!/bin/bash add(){ echo "Addition calculation" return `expr $1 + $2` } add 1 2 echo "Result of addition calculation: $?"
Operation results:
Addition calculation Result of addition calculation: 3
looks like we passed $? It seems right to get the result 3. However, by default, the return value of the function is 0-255. If it exceeds 0, it will start from 0. For example, calculating add 200 58 will get 2.
the return keyword in the Shell function is used to indicate the exit status of the function, not the return value of the function. If you must return other integers, define a global variable and change it in the function.
#!/bin/bash res=0 dosomething(){ echo "Addition calculation" echo "Other operations..." echo "Other operations..." res=`expr $1 + $2` } dosomething 200 58 echo "Result of addition calculation: $res"
Operation results:
Addition calculation Other operations... Other operations... Result of addition calculation: 258
12.3 function assignment description
see the following code
#!/bin/bash newAdd(){ echo "New addition calculation" echo "augend: $1" echo "Addend: $2" return `expr $1 + $2` } res=`newAdd 1 2` echo "Result of addition calculation: $res"
Operation results:
Result of addition calculation: new addition calculation Addend: 1 Addend: 2
we didn't get the expected result 3. In fact, res=`newAdd 1 2 'is to pass the standard output of function newAdd to res
epilogue
the syntax of Shell is relatively simple. Compared with other languages, it is different from the same. It mainly needs more practice and practice.