Series of articles:OC Basic principle series.OC Basic knowledge series.Swift bottom exploration series.IOS Advanced advanced series

preface

Before the article will talk about scripts, this article we have a good talk about shell scripts, talk about shell syntax, as for writing some scripts to perform some functions, I will also write some of the functions we often use it!

Shell syntax

Introduction of the Shell

  • Shell: aCommand line interpreter, under Unix operating systemThe most traditionaltheThe man-machine interface.
  • A Shell script:Explain to performThe,You don't need to compile, and most of themA programming languageIt’s similar. It’s basicvariableandFlow control statement

There are two ways to use Shell:

  • 1.Type the command.performThis method is calledInteractive;
  • 2.Batch mode, the user writes a Shell script file in advance and executes the commands in the script in sequence.

In addition to bash, the default Shell is now ZSH on macOS. It was developed by Paul Falstad in 1990. It is a Bourne Shell that uses the bash and Previous Shell features and adds more features:

  • 1.Spell checker
  • 2.Built-in programming features
  • 3.Friendly interaction

At the same time, macOS offers many other types of shells:

Bashrc,. Bash_profile, and. ZSHRC functions and differences

When using command line tools, we may encounter tutorials that require you to write configuration to.bashrc,.bash_profile, or.zshrc. So what are the functions and differences of these documents? Bashrc and.bash_profile are intended for Bash. ZSHRC is for ZSH.

Interactive login and non-login shells

When the Shell is called, the Shell reads information from a set of startup files and executes commands. What files are read depends on whether the Shell is called as an interactive login or non-login. In other words, shells are either interactive or non-interactive:

  • An interactive ShellisreadandwriteTo the userTerminal Shell program, the userEnter a command on the terminalAnd, inPress Enter to execute immediately.
  • Non-interactive ShellIs with theTerminal unrelated Shell programsFor example, when executing a script.

Configuration suggestions:

  • 1. Bash:
    • willPut the configuration options in ~/.bashrcAnd thenIn ~ /. FollowingIn theCall from source.
  • 2. The ZSH:
    • Advice is stillPut the configuration options in ~/.bashrc.~/.bash_profileIn theCall from sourceAnd the lastSource calls ~/.bash_profile in ~/.zshrc.

Common command reference: Linux command search, Linux command

Main Syntax introduction

annotation

Special symbols (emphasis)

  • 1.Double quotation marks "": used toContains a list of stringsIn theDouble quotation marks, in addition to"$", "\", "(back quotes)"In addition to its special meaning,Other characters, such as newline characters and carriage returns, have no special meanings.
  • 2.Single quotation mark ' ': single quotation marksThe function is similar to double quotation marks.But single quotesIn theAll characters have no special meaning.
  • 3.Back quotes: The function of backquotes isCommand substitutionIn theBack quote ' 'theThe content is usually the command line, the program willThe content in the backquotes is preferentially executedAnd,Replace the backquotes with the run result.

The dollar character is not displayed separately

  • 8.Parentheses ():Used to define an array variable.
  • 9.Double parentheses (()): Double brace commandAllows the use of advanced mathematical expressions during comparison.
  • 10.Brackets []:A singleIn parenthesesIt has the same function as the test commandBoth are used as conditional tests.
  • 11.Double brackets [[]]: Double brackets are providedAdvanced features for string comparisons, the use ofDouble brackets [[]] for string comparison, you canThink of the term on the right as a pattern, therefore, yesUse regular expressions in [[]].
  • 12.Curly braces {}: braces are used forEnclose a statement block.
  • 13.A colon (:)As aThe built-in command:Placeholders, parameter extension, and redirection. Note ⚠ ️ :Single and double quotation marks, the parentheses must beIn pairs.
  • 14.Expr commandIs an expressionComputational toolsUse it,Completion expressiontheEvaluate the operation.
  • 15.evaltobehindtheCmdLine scans twiceIf theFirst scanLater,CmdLine is a common command,Execute this command; ifCmdLine contains variablestheIndirect reference,Ensure the semantics of indirect references.

The output

  • 1.Standard input (STDIN): the code for0, use < or <<
  • 2.Standard output (STDOUT): the code for1, use > or >>
  • 3.Standard error output (STDERR): the code for2, use 2> or 2>>
  • 4.1 >To:coverThe way ofThe righttheData outputtoSpecify to fileorequipment
  • 5.1 > >To:cumulativeTo the wayThe righttheData output to the specified fileorequipmenton
  • 6.2 >To:coverThe way ofThe errortheData output to the specified fileorequipment
  • 7.2 > >To:cumulativeThe way ofThe errortheData output to the specified fileorequipment
  • 8.2>/dev/nullWill:Error to data discardAnd onlyShow the correctthedata
  • 9.2 > &1or& >Will:correctthedataanderrortheData is written to the same file
  • 10.> 1 & 2:The correct return value is passed to the 2 output channel.& 2said2 Output channel
  • 11.2 > &1:The error return value is passed to the 1 output channelAnd the same& 1said1 Output channel
  • 12.cmd: CMDCommand correlation is not considered.Continuous execution
  • 13. The current commandExecute successfullywillReturn a $? The value of = 0
  • 14.cmd1 && cmd2If:The first commandthe$?为0,Execute the second command
  • 15.cmd1 || cmd2If:The first commandthe$?为0,Do not execute the second command.Otherwise, run the second command
  • 16.|: The pipe can only be processedAn order came from the fronttheThe correct informationThat will beThe correct information is passed to the next command as stdin
    • 1. Pipe commandsOnly the correct output of the previous command is processed.Error output is not processed
    • 2. Pipe commandsOn the right side of the commandMust be able toReceive the standard input streamThe command to just go
    • 3. Most commands do not accept standard input as parameters. You can only enter parameters directly on the command line, which makes it impossible to pass parameters through pipe commands
  • 17.- :A minus signIn someCommand to get content from standard input (stdin)
  • 18.xargsIs:Convert standard input to command line arguments

run

Operation mode

  • 1.shUse:$sh script.sh Executes the scriptWhen the currentThe shell is the parent process, generate aA subshell processIn theExecute scripts in subshells. The scriptcompleted.Out of a subshell.Go back to the current shell.$ ./script.shwith$sh script.sh is equivalent. Also calledThe fork way
  • 2.sourceUse:$source script.sh, in the current contextExecute the script.No new processes are generated. The scriptcompletedAnd come back toThe current shell.$ . script.shwith$ source script.shEquivalent. You don’t need to have “execute permission.”
  • 3.The exec modeUse:The exec. / scriptsh way, will useThe command processreplaceCurrent Shell processAnd,Keep the PID constant.completed.Directly out ofDo not go back to the previous shell environment

Whether permission is required

  • 1.Sh /bash/ ZSH does not require "execute permission"
  • 2../script.sh requires "execute permission"
  • 3.Source script.sh does not require "execute permission"
  • 4.Exec needs to have "execute permission"

Variable definitions

  • 1.Shell variables default to strings. shellDon't care what this string means
  • 2. The Shell by defaultNumeric operations are of integer type. So if you want to doMathematical operations.Some command must be usedFor example, declare, EXPR, and double brackets
  • 3.Shell variables can be divided into two categories:
    • A local variable: creates them onlyThe shell is available. It’s defined inside the function, the functionIt is deleted after execution
    • The environment variable: can create them in theShell and any child processes derived from it. During the entire script execution, as long asIt exists until it's deleted
  • 4.Define the rules: The variable name must start withStarts with a letter or underscore character. Other characters can be letters, digits (0 to 9), or underscore characters. Any otherThe character marks the end of the variable name.Lower case sensitive
  • 5. When assigning a variable,There must be no whitespace around the equal sign
  • Usually 6.Uppercase characters are system default variables. Personal habits
  • 7. Set: View all variables (including environment variables and custom variables), andSets the new variable value of the shell variable
    • – a:Identifies modified variables for output to environment variables
    • – b:Causes the aborted daemon to report execution status immediately
    • E:If the command returns a value other than 0, exit the shell immediately
    • – f:Cancel the use of wildcards
    • – h:Automatically record the position of the function
    • – H Shell:Can use "!" Executes the command recorded in history with < command number >
    • K:The parameters given by the directive are treated as environment variables of the directive
    • – l:Record the variable name for the for loop
    • – m:Using monitor mode
    • – n:Read instructions without actually executing them
    • P: –Start priority mode
    • P: –When the -p parameter is enabled, the instruction is executed with an actual file or directory instead of a symbolic link
    • T: –After executing the subsequent command, exit the shell
    • – u:An error message is displayed when an undefined variable is used during execution
    • – v:Displays the input values read by the shell
    • – x:After executing the command, the command and its parameters will be displayed first
  • 8. Declare/typeset – aixrp variables
    • -a Define variables as arrays
    • -i Define variables as integers
    • -x Define variables as environment variables
    • -r Define the variable as readonly
    • P: –Shows how a variable is defined and its value
    • + :Cancel variable attributes, but+a and +r are invalid, cannot delete arrays and read-only properties, yesDelete an array using unset, butUnset cannot delete read-only variables
  • 9.The local keywordTo create variables in scope.The outgoing scope is destroyed
  • 10.Export is the shell variableorFunction to set the export properties, becomes the environment variable. Cannot add export attributes to undefined functions. At the same time, it’s important to note,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:Represents [variable name] is the function name
    • – n:Deletes the exported attribute 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
    • The zanu-pf:Displays all functions that have exported attributes
    • Nf:Deletes the export attribute of the function
    • – :Options after it are invalid
  • 11. A wildcard
    • * :Matches any string, including empty strings, excluding the '/' character
    • ? :Matches any single character, but cannot match the slash character
    • [ABC] :Matches characters a, B, or C
    • [ABC] ^ :Does not match the "A" or "B" or "C" characters
    • [a-z] :Matches any of the 26 lower-case characters
  • 12. WithThe set commandcanLook at all the variables.The unset var commandcanClear variable varVar is not defined.readonly varcanMake var a read-only variable, after definitionYou cannot make any changes to var

Parameter expansion

    1. Indirect parameter extension
    • ${parameter – string} :If parameter is not set, it is replaced with string and the parameter value is not changed. Otherwise, no processing is performed
    • The ${parameter = string} :If parameter is not set, it is replaced with string and the parameter value is changed. Otherwise, no processing is performed
    • ${parameter? String} :If parameter is not set, string is printed to standard error. Otherwise, no processing is performed
    • The ${parameter + string} :Replace parameter with string when parameter is empty. Otherwise, no processing is performed
    • ⚠ ️The ${! Parameter}, not supported by ZSH
  • 2. Colon followed by equal sign, plus sign, minus sign, question mark (⚠️ can not have Spaces)
    • ${parameter:-string} : If parameter is not set or empty, replace it with string
    • ${parameter:=string} : If parameter is not set or empty, replace it with string
    • ${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
  • 3. Substring extension:${parameter:offset}and${parameter:offset:length}. fromThe offset position starts to intercept the lengthIs a substring of length, starting at offset and ending at offset if no length is provided
    • Offset can be negativeAnd,Must be separated from the colonorWith (). The starting position is from the end of the string, and thenTake a substring of length. For example, -1 means to start with the last character
    • The parameter is @, that is,All positional parameters, offset must start from 1
  • 4) replacement:${parameter/pattern/string},${parameter//pattern/string},The ${parameter/pattern} and ${parameter / / the pattern}. Case sensitive. If string is empty, thenThis is equivalent to deleting the matching substring. If after parameterIs /,Matches only the first substring encountered; If after parameterIt is / /.Matches all substrings
  • 5. Delete:${parameter#pattern},${parameter##pattern},${parameter%pattern}and${parameter%%pattern}
    • # is to remove the left side.% is to remove the right hand side. A single symbol is a minimum match; Two symbols is the maximum match
  • ${#parameter}

The test and judgment

Multi-branch statement judgment

  • Except for the last branch, which can be a normal or * branchEach branch must begin with; At the end.;; Represents the end of a branch.Don't writeIt will beThere are grammatical errors.The last branchcanWriting;;Also,Can not writeBecause no matter what,Perform the esacEnds the entire case in statement.

  • [] : judgment symbol,Two equalsandAn equal sign, the effect is similar
    • 1. The ones in bracketsEach component needs to be separated by Spaces
    • In the 2.Parenthesis variable.Use double quotation marks
    • In the 3.Constant of parentheses.Use single or double quotation marks

Test Command test

  • 1.test n1 -eq n2:
    • – eq:equal
    • – ne:Ranging from
    • Gt:Is greater than
    • Lt:Less than
    • Ge: –Greater than or equal to
    • – le:Less than or equal to
  • 2. String judgment
    • Z string:Checks if string is 0, null, or true
    • The -n string:Check if string is non-0, null, or false
    • String1 equals string2.Are strings equal?.Is equal to true
    • string1 ! = string2:Are strings unequal?.Equal to false
  • 3. Multiple conditional judgment
    • – a:Both conditions are true
    • – o:If either condition is true, it is true
    • ! :reverse
  • 4. Determine the file type
    • E:File name exists
    • – f:Whether the file name exists and is a file
    • – d:Whether the name exists and is a directory
    • – L:Whether the name exists and is a linked file
  • 5. Check file permissions
    • – r:Whether it exists Whether it has the read permission
    • – w:Exists Indicates whether the user has the write permission
    • – x:Exists Indicates whether the executable permission is available
    • S:Whether the file exists and is not blank
  • 6. Compare the two files
    • -nt Is file 1 newer than file 2
    • -ot Is file 1 older than file 2
    • -ef Check whether file 1 and file 2 are the same

cycle

Wrote last

This article is my summary of shell language syntax, preparing for writing shell scripts in the future. In the next shell script, the syntax introduced in this article will not be explained any more. If you have any questions, you can leave a message below, and HOPE we can communicate more and give a thumbs-up!