High-level languages, scripting languages, interpreted languages: xxx.sh, generally based on bash
Course Content#
First Shell Script#
#!/bin/bash
# Comment
echo "Hello"
- The first line #! specifies the interpreter, valid only on the first line
- Comment: "#"
Variables#
a=123
a=hello
a=`pwd`
PATH=${PATH}:path # A string can be directly concatenated after a variable
# 【Note】":a" has a special meaning, pointing to the current path
- No need to define variable types【Weakly typed language】
- For example, a=123 can be a string or an integer
- "" has a special meaning
Special Variables#
Positional Variables
Result:
-
$n: If n > 9, it needs to be enclosed in braces
-
$@ and $* differ in that: when passed parameters are enclosed in double quotes, and the $ variable is also enclosed in double quotes, "$@" will separate all parameters【general case】, while "$*" will treat all parameters as a whole
- This can be seen when using for...in, see Shell special variables: Shell $0, $#, $*, $@, $?, $$ and command line parameters——C Language Chinese Network
-
$# : does not count $0
Status Variables
- $? : [The result of the last] command execution, 0——success, non-0——failure
- Facilitates automatic judgment of command success in scripts
- $$ and $! : PID of the current process and the last running background process, generally used in automated testing and multi-script interaction scenarios
Input and Output#
- Input: read
- -p: Displays friendly prompts, needs to be used in bash
- -s: Silent mode
- -t: Input wait duration, timeout ends (unit: s)
- Output: echo
- -e: Enable escape
- Output: printf
- Very similar to C language's printf!
- [PS] ! and \n have special meanings when used together, need to be separated
- Needs to be separated in bash
- Can be separated in zsh, or escaped with \
- Generally for special symbols——Beginner's Tutorial, need to be cautious!
Functions#
-
No parameters
-
Definition: Many ways to write, function, () and {} combinations, the third way is more similar to C language writing
-
Call: function name parameters...
- Adding function for readability
-
❗【Note】The return value of functions in shell is limited, the range is 0-255, overflow will cycle and recalculate
Control Flow#
do——done, if——then——fi, case——esac
【Key Point】TEST Expression⭐#
- Can judge types: string, integer, file
- ❗ 【Note】When the condition is true, it returns 0, otherwise returns non-0
- The return value of commands in Linux is also like this, 0 represents success
- [PS]
- STRING1 = STRING2 can also use == 【Recommended later, two brackets [[ ]] support】
- -G FILE: The file exists and is owned by a valid group ID
- If the group is dissolved, the group ID of the file controlled by the group becomes invalid
- For specifics, refer to the man manual: man test
Branch Structure#
if
-
Using two brackets [[ ]] for if is more advanced and has better compatibility with TEST expressions
- One bracket [ ] is an older writing style, not recommended, use two brackets
- Refer to The role of ()、(())、[]、[[]]、{} in Linux Shell——Blog
case
-
The semicolon ;; cannot be omitted! Equivalent to break, and if break is added, it must also be present
-
Default case can use *)
-
case is used less often, generally for menus, more aesthetically pleasing than if
Loop Structure#
for
-
Use seq to generate sequences
-
Use ls matching rules
-
Two forms of for
-
The content in double parentheses (()) only needs to comply with C language operation rules, variables can be written without the variable prefix $, can write i++, normally cannot use ++
while
-
Also applicable to test expressions
-
Initialize num variable, otherwise
- The first time echo $num, $num is empty, resulting in an empty line
- When encountering the subsequent +1, the system determines it as an integer type, and only then is it treated as an integer
until
-
The only difference from while is: until writes the stop condition, while writes the loop condition
Arrays#
-
Array assignment【Method ①】 and calling
-
【Common array operations】 can also output the index of array elements, see below
-
Declare array: declare -a num, for readability, can also be done without declaration [Weakly typed language]
-
Assignment【Method ②、③】
- num[2]=10 num[5]=7 num[100]=3.2.4
- num=(1 a b 10)
-
Array elements do not have to be assigned continuously and can be of any type
- 【Common array operations】 add !: output all array elements' corresponding indices, can see they are not continuous
【Other Array Operations】
-
+=: Append
-
unset: Delete array or element [delete by index]
-
[PS] Assignment method ③ treats multiple spaces as a single separator
Application
-
Can be used to store a list of file names
-
【Note】Assignment method ③ assigns values to arrays using spaces as separators, so if file names contain spaces, special handling is needed
-
【PS】Prime sieve, linear sieve
In-Class Exercises#
Sum of Even Numbers from 1 to 100#
-
$[ ] can be used for integer operations
-
seq is slightly less efficient
Bruteforce Prime Calculation#
-
The return value of functions
- Obtained through $?, after calling the function echo $? can get it, but the return value has a range limit of 0~255!
- Obtained through command substitution ``
-
Note the conflict issue with the loop variable i: define local variables
-
🆒 Debugging the program
- Habit: Appropriate echo output
- Global debugging: bash -x *.sh
- Local debugging: set -x [debug code area] set +x
Prime Sieve#
-
Method one is convenient for operating primes and can reduce judgment during output
-
Method two can also operate composite numbers
【Comparison of two methods: Bruteforce and Prime Sieve】Calculate the sum of primes from 2 to 10000
- 9.prime.sh Bruteforce —— 10.prime.sh Prime Sieve
Additional Knowledge Points#
- .sh scripts can be executed directly with bash or source, if using ./ it requires executable permissions
- set -x can enable shell debugging
- Shell Command Substitution: Assigning the output of a command to a variable——C Language Chinese Network
- $() supports nesting, backticks `` do not
- $() is only valid in Bash [seems zsh and sh also support], while backticks `` can be used in various shells
- Content in double parentheses (())
- Only needs to comply with C language operation rules
- Variables can be written without the variable prefix $
- Can write i++, normally cannot use ++
- ⭐ In Shell, when a variable is not yet defined, its value is empty, echo output appears as an empty line
- ⭐ Space issues【Strict】
- In assignment statements: = cannot have spaces on either side
- Related to TEST expressions: [[ ]] must have spaces on both sides
- For variable name i, if you want to concatenate $i with _i, using $i_i will look for variable i_i, so use ${i}_i
Tips#
- Writing Shell scripts
- Do not worry too much about performance, purely doing mathematical calculations is inefficient
- The goal is to quickly solve a problem and plan the flow of all tasks
- Remember to add【backup】 operations before performing actions
- Generally, it is about letting the system do things, which is harder than making specific programs do things
- Programs generally have their own parameter settings but lack universality
- API generally refers to services
- ⭐Shell Style Guide——Google Open Source Project Style Guide——Shell Programming Specifications
- Methods for multi-line comments and single-line comments in Shell scripts——Blog
:<<!
[Code to be commented]
!
- You can learn about let——Beginner's Tutorial, convenient syntax