A shell is a command line interpreter, and commands like our terminal commands are written in C or C++

The shell is used as a glue to hold together the commands we commonly use

#! / bin/bash:

Refers to the path to use the shell: <<! Shebang (Hashbang) : A sequence of characters #! The first two characters that appear on the first line of a text file. The program loader of the operating system parses the contents of the Shebang as interpreter instructions. And calls the directive, taking the path of the file containing Shebang as an argument to the interpreter. #! /usr/bin/python #! /usr/bin/env pyhon env: The script interpreter may be installed in a different directory and set to the PATH of the system depending on the operating system. Env can be found in the PATH directory of your system. The command above uses the first Python version found in the user path. However, you can specify a version number: #! /usr/bin/env pythonx. x env can also specify the search directory: #! The/usr/bin/env - S - P/usr/local/bin: / usr/bin: ${PATH} python will in/usr/local/bin, / usr/bin, the system PATH search python. Child process: To open a new shell under the current shell. PS1 prompt definition: Prompt set [\u@\h \w \A #\#]\$1. \h host name abbreviation 2. \u user account name 3. \w full working path 4. Otherwise, $HOME: represents the user HOME folder. SHELL: which SHELL is currently in use PATH: execute file search PATH read [-pt] variable Read keyboard variables for example: read a is to assign the keyboard value to a variable -p: prompt -t: wait seconds!Copy the code

Multiline comment

  • “# echo” single line comment”

: < <! Echo “multiline comment”

<< COMMENT Mode 2: echo “COMMENT”

Echo “echo”;

if false; Then multiline comment mode 4: echo “multiline comment” fi

((0)) && {echo “echo”}

Special symbols

COMMENT 1. Double quotation marks "" : The double quotation marks are used to contain a group of character strings. Except for "$", "\", and" (back quotation marks)", the other characters (such as newline characters and carriage returns) have no special meanings. In scripting languages, traversal is a string by default, but special characters must be enclosed in double quotation marks to avoid ambiguity. 2. Single quotation marks ": The function of single quotation marks is similar to that of double quotation marks, but all characters in single quotation marks have no special meaning. 3. Backquotes: The function of backquotes is command replacement. The content in backquotes is usually a command line. 4. $+ parentheses $() : functions like backquotes and is a command replacement. 5. $+ double parentheses $(()) : $(()) is used to perform arithmetic operations, and the contents in parentheses are mathematical expressions. $((20 + 5 * 6)) returns the result of the arithmetic operation in double parentheses. $[] : $[] is the same as $(()). ${} : ${} functions as a variable reference, like the $character, but ${} is more exact than the replacement range of $. 8. Parentheses () : Define an array variable. 9. Double brace (()) : The double brace command allows advanced mathematical expressions to be used during comparisons. 10. Brackets [] : The single brackets function as a conditional test, just like the test command. 11. Double brackets [[]] Double brackets provide advanced features for string comparison. When using double brackets [[]] for string comparison, the item on the right can be regarded as a pattern, so regular expressions can be used in [[]]. Braces {} : Braces are used to enclose a statement block. 12. Colons (:) as built-in commands: placeholders, parameter extensions, and redirects Note ⚠️ : single and double quotation marks, parentheses must be paired. 13. The expr command is an expression evaluation tool that can be used to evaluate expressions. Eval scans cmdLine twice. If cmdLine is a normal command after the first scan, eval executes this command. If cmdLine contains indirect references to variables, the semantics of indirect references are guaranteed. Type: displays command attributes. The location of the command is displayed. Echo [-ne][string] : print the string according to the rule. -n do not wrap at the end of the string. \b Delete previous character; \c produces no further output (characters after \c do not output); \f Newline but the cursor remains in the original position; \n Newline and cursor moved to the beginning of line; \r Moves the cursor to the beginning of the line without newline; \t Insert TAB; \v is the same as \f; \\ insert \ character; \ NNN Inserts the ASCII character represented by NNN (octal); Echo -e "\e[1;31mThis is red text\e[0m" \e[1;31m Set the color to red \e[0m set the color back to the color code: Reset =0, Black =30, red =31, green =32, yellow =33, blue =34, magenta =35, cyan =36, white =37 Background color: echo -e "\e[1;42mGreed Background\e[0m" Reset =0, Black =40, Red =41, Green =42, Yellow =43, Blue =44, Magenta =45, cyan =46, White =47 Echo - e "\ [37, 31, 033 5 mlogic Cat handsome handsome... \ [39, 49, 033 0 m" red Numbers and other digital parameters: 0 to close all attributes, 1 set high brightness (bold), 4 underlined, 5, 7 reverse video, 8 blanking the COMMENT 'Copy the code

Search for the weak string from the test.m file

# grep weak --color=auto --.. # grep weak --color=auto --.. /Common\ Symbol/test.m grep weak --color=auto -- ".. /Common Symbol/test.m" # error grep weak --color=auto -- ".. /Common\ Symbol/test.m" # error grep weak --color=auto -- '.. /Common\ Symbol/test.m'Copy the code

Standard input and standard output

  • Cat: This command is used to view the contents of a file
    • If there’s nothing behind it, it’s standard input, it’s going to print out what’s in it, so you can use control + D
    • Cat + > + file name: This will wait for keyboard input, after the keyboard input is written to the file
    • Cat + > + file name + character A: In this case, the input will wait for the required content, and then you can use character A to end the input. Generally, the default end character is eof
    • Echo + character A + &>&1: followed by &1 for standard input, &>&1 for relocating both standard input and standard error to the same place
COMMENT (stdin) : code 0, use < or <<; Standard output (STDOUT) : code 1, use > or >>; Standard error output (STderr) : code 2, use 2> or 2>>; 1> Overwrite the correct data to the specified file or device; 1>> Output the correct data to the specified file or device using the summation method; 2> Overwrite the wrong data to a specified file or device; 2>> Output the wrong data to the specified file or device in a cumulative manner; < standard input; << end input, followed by an end input character; 2>/dev/null discard error data and display only correct data; 2>&1 or &> writes the correct data and the wrong data to the same file; The correct return value of 1>&2 is passed to the 2 output channel &2 represents the 2 output channel; The error return value of 2>&1 is passed to the 1 output channel, and again &1 represents the 1 output channel; cmd; CMD executes continuously regardless of command dependencies. If a command is successfully executed, a $? The value of = 0. Cmd1 &&cmd2 if the $? If the value is 0, run the second command. Cmd1 | | cmd2 if the first command $? If the value is 0, the second command is not executed. Otherwise, run the second command. The pipe can only process the correct information from the previous command, passing the correct information to the next command as stDIN (standard input). 1. Pipeline command only processes the correct output of the previous command, not the wrong output; 2. The command on the right of the pipe command must be able to receive the standard input stream command. 3. Most commands do not accept standard input as arguments, and can only be entered directly on the command line, which makes it impossible to pass parameters through pipe commands. - : the minus sign in some commands means to get the content from the standard input (stdin), just as a hint, can not be xargs: is to convert the standard input to the command line argument COMMENT'Copy the code

Three ways to execute a shell

Sh: When $sh script.sh is used to execute the script, the current shell is the parent process and a subshell process is generated to execute the script in the subshell. After the script is executed, exit the subshell and return to the current shell. $./script.sh is equivalent to $sh script.sh. 2. Source: $source script.sh is used to execute the script in the current context without generating a new process. After the script is executed, return to the current shell. In this case, variables created during script execution do not destroy $.script. sh equivalent to $source script.sh. 3. Exec mode: Exec./scriptsh mode replaces the current shell process with command and keeps the PID unchanged. After the command is executed, exit directly without returning to the previous shell environment. Sh /bash/ ZSH does not require "execute permission" 2... /script.sh does not require "execute permission" 3. Source script.sh does not require "execute permission" 4.Copy the code

Definition of variables

: 'COMMENT 1. The Shell variable defaults to a string. The shell doesn't care what this string means. 2. The Shell's default numeric operations are integers. Therefore, to perform mathematical operations, you must use commands such as DECLARE, expr, and double parentheses. 3. Shell variables can be divided into two categories: I. Local variables: only available in the Shell in which they were created. It is defined within a function and deleted after the function is executed. Ii. Environment variables: They can be used in the shell that created them and in any child process derived from them. It persists as long as it is not deleted during the entire execution of the script. 3. Define rules: Variable names must begin with a letter or underscore character. Other characters can be letters, digits (0 to 9), or underscore characters. Any other character marks the end of the variable name. Lowercase sensitive. 4. When assigning a value to a variable, there should be no whitespace around the equal sign. 5. Uppercase characters are the default variables. Personal habits. 6. Set: View all variables (including environment variables and custom variables) and set new variable values for shell variables. -a: identifies modified variables for output to environment variables. -b: Enables the stopped background program to report the execution status immediately. -e: Exits the shell immediately if the command returns a value that is not equal to 0. -f: Cancels the wildcard. -h: automatically records the position of the function. -h Shell: can use "!" Executes the command recorded in history with < command number >. -k: The parameters given by the command are regarded as the environment variables of the command. -l: Records the variable name of the for loop. -m: indicates the monitoring mode. -n: reads the command but does not execute it. -p: enables the priority mode. -p: After the -p parameter is enabled, the command is executed with an actual file or directory instead of a symbolic link. -t: exits the shell after the command is executed. -u: An error message is displayed when an undefined variable is used. -v: displays the input values read by the shell. -x: displays the command and its parameters after the command is executed. Declare /typeset [-aixrp] variable -a defines a variable as an array -i defines a variable as an integer -x Defines a variable as an environment variable -r Defines a variable as readonly -p: Displays the definition of a variable and its value + : Cancels variable attributes, but +a and +r are invalid. Arrays and read-only attributes cannot be deleted. You can use unset to delete arrays, but unset cannot delete read-only variables. 8. The local keyword, used to create variables in scope. The outgoing scope is destroyed. 9. Export Sets the export properties for shell variables or functions to become environment variables. Cannot add export attributes to undefined functions. At the same time, it is important to note that export is only valid for this login operation. Log out or open a new window, and the environment variables given by the export command no longer exist. -f: indicates that [variable name] is the function name. -n: Deletes the exported attributes of a variable. Variables are not actually deleted, but are not printed to the execution environment of subsequent instructions. -p: displays all variables that have exported attributes. -pf: displays all functions that have exported attributes. -nf: deletes the exported attributes of a function. -- : Options after it are invalid. 10. Wildcard * : matches any character string, including empty character string, excluding slash character. ? : Matches any single character, but cannot match the slash character. [ABC] : matches characters a, B, or C. [^ ABC] : does not match "A" or "B" or "C" characters. [a-z] : matches any of 26 lowercase characters. Using the set command, you can view all variables. Using the unset var command, you can clear the variable var. Readonly Var You can change a var to a read-only variable. COMMENT'Copy the code

Property operators:

  • Expr 3 + 4 is used to perform mathematical operations, but only if there is a space between a number and an operator. All operators and variables require Spaces, otherwise they are recognized as consecutive strings.
  • Reslut=$(( 3 + 4 ))

If you want to get the return value of the expR formula, you need to wrap the expression around it, for example

Reslut=`expr 3 + 5`
Copy the code

The value of a variable can be read in either of the following ways, which have the same effect. If the first expression is ambiguous, the second expression is required

  • echo “$Reslut”
  • echo ${Reslut}

In the.bash_profile file, we see the following statement:

export PATH=/Users/zhaojing/opt/flutter/bin:$PATH
Copy the code

Add the value of the previous part of the PATH and assign the value to it

Set: set variable keyword, the following is a separate set variable statement, remember to delimit by a space

set 11 12 13
Copy the code

Parameter selection method:

Echo "$#" echo "$@" // Eval can be executed twice. The first time $# is executed, the statement becomes $5. The second time is executed, the statement becomes $5. $# eval echo "\$$#"Copy the code

function

Function name () {function name () {function name () {function name () {function name () {function name ()} 1. If there is funtion, you may not write (), and if there is no function, you must write (). Variables defined in the shell are global by default, and are preceded by local 2 if they are only useful in functions. There must be a space between the function name and {. 3. Formal parameters shall not be declared. 4. The function must be declared before calling the function. 5. 7. By default, a function that does not return a value returns the value of the last instruction in the function. A function with a return value can only return an integer. 8. To obtain the function value, only $? To obtain. The value obtained by = is null. We can think of a shell function as defining a new command, so the input parameters are separated by Spaces. $0... $0... $n. $0 represents the function itself. $# : The number of arguments passed. $* : All positional arguments (as a single string). $@ : All positional arguments (each as a separate string). $? : The return value of the last command in the current shell process. If the last command was executed successfully, then $? Is 0, otherwise is other non-zero values. $$: pid of the current shell process. $! : PID of the last process running in the background. $- : displays the current options used by the shell. $_ : The last argument to the previous command. COMMENT'Copy the code

Function example

Logic function DoWork {local LG_CAT=" LG_CAT "echo "logic" return 2} DoWork() {local LG_CAT=" LG_CAT" echo "logic" Logic function DoWork {local LG_CAT=" LG_CAT "echo "logic" return 2} echo $LG_CAT echo 'DoWork' No output Logic function DoWork {LG_CAT=" LG_CAT "echo "logic" return 2} echo $LG_CAT echo 'DoWork' logic function DoWork { LG_CAT="LG_Cat" echo "logic" return 2 } echo `DoWork` echo $LG_CAT logic logic LG_Cat function DoWork { LG_CAT="LG_Cat" echo "logic" return 2 } DoWork echo `DoWork` echo $LG_CAT logic 2 logic 0 function DoWork { LG_CAT="LG_Cat" echo "logic"  return 2 } DoWork echo "$?" echo `DoWork` echo "$?" Function DoWork {echo" \n \$#:$#\\n \$0:$0\\n \$1:$1\\n \$2:$2\\n \$*:$*\\n \$@:$@\\n \$$:$$\\n \$-:$-\\n \$_:$_ " return 2 } DoWork "Cat" "LGCat"Copy the code

Extension of parameters

: 'COMMENT parameter extension: Gets the value stored in the parameter with the $symbol. I. ${parameter-string} : if parameter is not set, replace it with string. Otherwise, no processing is performed. ${parameter=string} : if parameter is not set, change the parameter value to string. Otherwise, no processing is performed. iii. ${parameter? String} : parameter is not set, then string is printed to standard error. Otherwise, no processing is performed. Iiii. ${parameter+string} : replace parameter with string when parameter is empty. Otherwise, no processing is performed. The ${! I. ${parameter:-string} : if parameter is not set or empty, the parameter value is replaced with string. ${parameter:=string} : ${parameter:=string} : If parameter is not set or empty, replace it with string. iii. ${parameter:? String} : If parameter is not empty, the value of parameter is used. If empty, the string is printed to standard error and exits from the script. ${parameter:+string} : replace parameter with string if parameter is not empty. If null, do not replace or replace null values. ${parameter:offset} and ${parameter:offset:length}. A substring of length is intercepted from offset, or from offset to end if no length is provided. I. Offset can be negative and must be separated by colons or wrapped with (). The starting position starts at the end of the string and takes a substring of length. For example, -1 means to start with the last character. Ii. parameter is @, that is, for all positional parameters, offset must start at 1. 4) replacement: ${parameter/pattern/string}, ${parameter / / pattern/string}, ${parameter/pattern} and ${parameter / / the pattern}. Case sensitive. If string is empty, the matching substring is deleted. If the value after parameter is /, only the first substring encountered is matched. If the parameter is followed by //, all substrings are matched. ${parameter##pattern}, ${parameter##pattern}, ${parameter%%pattern} and ${parameter%%pattern} are deleted. I. # is remove left side, % is remove right side. A single symbol is a minimum match; Two symbols is the maximum match. ${#parameter} COMMENT'Copy the code

Extended examples of parameters

LONG_LONG_STRING="I am Cat! CAT! Cat! Cat" # # Some string # echo "${! VALUE}" # # # echo "${FOO-"Cat-"}" # # Cat- # echo "${FOO="Cat-"}" # # # echo "${FOO+"Cat-"}" # # Cat- # echo "${FOO?" Cat----"}" # # Cat- # echo "${FOO:-"Cat-"}" # # Cat= # echo "${FOO:="Cat="}" # # Cat= # echo "${FOO:?" Cat?" }" # #Cat+ # echo "${FOO:+"Cat+"}" # #Cat\ # echo "${LONG_STRING:5}" # #Cat # echo "${LONG_STRING:5:3}" # #Cat # echo "${LONG_STRING: -4:3}" # #Cat # echo "${LONG_STRING: -4:3}" # #Cat # echo "${LONG_STRING:(-4):3}" # # I am Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING/cat}" # # I am LGCat! CAT! LGCat! LGCat # echo "${LONG_LONG_STRING//Cat/LGCat}" # # am Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING#* }" # # am Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING#? }" # # at! CAT! Cat! Cat # echo "${LONG_LONG_STRING#*[Cc]}" # if [[ -n $IS_ZSH ]]; then # # Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING#*(AT|m)}" # echo "-----${LONG_LONG_STRING#*(AT|m)}" # echo "-----${LONG_LONG_STRING#[A-z]**(AT|m)}" # # ! Cat! Cat # echo "-----${LONG_LONG_STRING#*(AT|mm)}" # fi # # m Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING#*[a-t]}" # # m Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING#*[a-t]}" # # am Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING#*[^A-Z]}" # echo `echo "./*.sh"` # echo `echo "./"*.sh` # # Cat! CAT! Cat! Cat # echo "${LONG_LONG_STRING##* }" # # at # echo "${LONG_LONG_STRING##*[Cc]}" # # # echo "${LONG_LONG_STRING##*[a-t]}"  # # I am # echo "${LONG_LONG_STRING% *}" # # I # echo "${LONG_LONG_STRING%% *}" # # 20 # echo "${#LONG_LONG_STRING}" # # i am cat! cat! cat! cat # echo "$(echo "${LONG_LONG_STRING}" | tr "[:upper:]" "[:lower:]")" # # I AM CAT! CAT! CAT! CAT # echo "$(echo "${LONG_LONG_STRING}" | tr "[:lower:]" "[:upper:]")" # if [[ -n $IS_ZSH ]]; then # # I AM CAT! CAT! CAT! CAT # echo "${LONG_LONG_STRING:u}" # # i am cat! cat! cat! cat # echo "${LONG_LONG_STRING:l}" # fiCopy the code

Multi-branch statement judgment

The statement is a function

The COMMENT statement determines that all branches except the last branch (which can be normal or *) must end with;; At the end,;; Represents the end of a branch. If you don't write it, you'll get a syntax error. The last branch can be written;; , or not, because executing to ESAC ends the entire case in statement anyway. Case $variable in "first variable content "); *) *); esac COMMENT'Copy the code

conditional

'COMMENT ': if [condation]; If [condation]; if [condation]; Then founded elif [Condation]; Fi COMMENT'Copy the code

statement

: 'COMMENT [] : judgment symbol, two equal signs and one equal sign, similar effect. 1. Each component in brackets must be separated by a space. 2. Bracketed variables, with double quotation marks 3. Bracketed constants, with single or double quotation marks COMMENT'Copy the code

Judgment key word

Test n1 -eq n2: -eq: equal -ne: equal -gt: greater than -lt: less than -ge: greater than or equal to -le: less than or equal to 2. -z string: Checks whether the string is 0. If the string is empty, the value is true. -n string: Checks whether the string is non-0. If the string is empty, the value is false. String1 = string2: indicates whether the strings are equal. string1 ! = string2: whether the strings are unequal. If they are equal, the value is false. 3. Multiple condition judgment - A: If both conditions are true, the value is true. -o: indicates that either condition is true. ! : the reverse. 4. Check the file type. -e: Indicates whether the file name exists. -f: Indicates whether the file name exists and is a file. -d: Indicates whether the name exists and is a directory. -l: Indicates whether the name exists and is a linked file. 5. Check file permissions. -r: Indicates whether the file has readable permissions. -w: Indicates whether the user has the write permission. -x: Indicates whether the user has the execution permission. -s: Indicates whether the file exists and is not blank. 6. Compare two files - whether nt file 1 is newer than file 2. - OT File 1 is older than file 2. -ef Whether file 1 and file 2 are the same. COMMENTCopy the code