In the front-end development process, the project batch script, timing script, and some scripts of the deployment server, if using NodeJS to write, it will rely on the Node development environment by default, but may need these in fact have nothing to do with Node, PHP, Python, etc. Therefore, I thought of shell script, the scripting language compiled by the underlying kernel, so I am fully familiar with and understand it.

1: What is a shell?

Shell translates as Shell, which is a Shell covering the outer layer of the operating system. It parses the user’s commands into commands that can be executed by the kernel and plays a role of command interpretation. It is a direct bridge between the user and the operating system. Shell scripts have a unique and irreplaceable role in batch/scheduled tasks because of their direct interaction with the Linux system.

Currently, the mainstream CLI Shell on Linux systems is Bash, which is the default Shell for many Linux distributions. Note Run cat /etc/shells on Linux to check the Shell types supported by this version, and run the echo $Shell command to check the default shells in the current environment.

You can see from the picture abovemacThere are many different types of support.

1:Common interpreters:

  • bash: BashisBourne shellA substitute for, genusGNU Project, the binary file path is usually/bin/bash. The industry often uses them interchangeablybash,sh, andshell.
  • sh: the standardshellInterpreter, whose binary file path is usually/bin/sh

2:The execution environment:

The current mainstream operating systems all support shell programming, which is based on POSIX standards. Therefore, it is also applicable to Unix and BSD (such as Mac OS).

  • Linux: LinuxIt is installed by defaultshellThe interpreter.
  • Mac OS:Mac OSNot only with thesh,bashThese two basic interpreters are built inksh,csh,zshAnd other uncommon interpreters.
  • Emulator on Windows: git bash.

3:Common application scenarios::

  • Application installation:ShellScripts are suitable for repetitive tasks, such as installing and configuring some software or configuring the environment for repeated use.
  • Scheduled task:ShellScripting is great for cyclical work;
  • Application operations: for example, we write our own applications, we can write scripts for the start, stop, restart and other operations, add the script into the system environment, the later is very convenient for service management;
  • Backup and recovery: you can use scripts for site files or database remote backup, and restore to the test environment for verification;
  • CI/CD: ShellScripts are applicable toDevOPSContinuous integration and continuous deployment in the serverpipelineThe configuration is applicable to the last kilometer of application publishing.

2: Start your shell programming journey

1: Basic specification

  • The general is.shAs a suffix. Can also be/bin/php test.php. The extension has no effect on execution.
  • The first line needs to specify the interpreter, for example#! /bin/bashHowever, this method has some limitations and we recommend itenvIn environment variablesbash, this method is recommended#! /usr/bin/env bash.

You can check the node path setting for which node.

For example, the hello.node /hello.sh file

#! /usr/bin/env node console.log(process.execPath); // Output /usr/local/bin/node console.log(1);Copy the code

#! The/usr/bin node and #! /usr/bin/env node

! /usr/bin/node: tells the operating system to execute this script by calling the node interpreter in /usr/bin and writing down the path. ! /usr/bin/env node: This is used in case the operating system user does not install node in the default /usr/bin directory. When the system sees this line, it first looks up the node installation path in the env setting, and then calls the corresponding path interpreter to complete the operation. Will go to the environment Settings to find the Node directory, this method is recommended.

2: operating mode

  • Specify the script file name on the terminal to execute the script. In this mode, you need to add the executable permission to the scriptShellTo execute, no promoterShell.chmod +x test.sh If you run it directly from the console, an error will be reportedpermission denied.
  • Command to execute the script, generally used in the current directory is not inPATHMiddle, so the second one. /Is used to represent the current directory,eg:. ./banner.sh.
  • directlysourceExecute to specify the compiler:bash ./banner.sh

3: debugging mode

bash -x banner.sh
Copy the code

Debug mode will be turned on and the print results will be displayed each time.

4: Bash common symbols and tools and keyboard shortcuts

  • Semicolon (;) Is the end of a command, so that multiple commands can be placed on one line. After the execution of the previous command is complete, the second command can be executed.

clear; Ls -l: Indicates that ls -l is executed regardless of whether the clear command is executed successfully.

  • && must execute the former successfully before executing the latter. cat filelist.txt && ls -l filelist.txt

  • | |, mkdir foo | | mkdir bar behind only failed to perform in front of the executive.

  • Type: Bash itself comes with many commands built in, and external programs can also be executed. How do you know if a command is a built-in command or an external program?

$ type echo  # echo is a shell builtin
$ type type  # type is a shell builtin
Copy the code
  • Combination shortcut keys:
    • Ctrl + U: Deletes from the cursor position to the beginning of the line.
    • Ctrl + K: Deletes from cursor position to end of line.
    • Ctrl + A: Moves the cursor to the end, corresponding toEThat’s the tail.
    • Bang (!) Command:!!!!!: Execute the last command,! cc: Executes the most recent command starting with cc, such as! L will run the ls command

5: variable

5.1: Environment variables
BASHPID: indicates the Bash process ID. BASHOPTS: parameters of the current Shell, which can be modified using the shopt command. HOME: indicates the HOME directory of the user. HOST: indicates the name of the HOST. IFS: Delimiter between words. Default is space. PATH: A list of directories separated by colons that will be searched when an executable name is entered. PS1: Shell prompt. PS2: Secondary Shell prompt when typing multi-line commands. PWD: indicates the current working directory. RANDOM: Returns a RANDOM number between 0 and 32767. SHELL: indicates the name of the SHELL. SHELLOPTS: Arguments to start the set command of the current Shell. See the set command chapter. UID: indicates the ID of the current user. USER: indicates the name of the current USER.Copy the code

For example, the following script gets user information:

    #!/bin/bash
    echo ${USER} ${USER}
    echo $(date +")%Y-%m-%d %H:%M:%S")"
    echo "Shell: ${Shell}"
    echo ${HOME} = ${HOME}
Copy the code
5.2: Custom variables
5.2.1 Naming Rules:
  • The value contains letters, digits, and underscores (_).
  • The first character must be a letter or an underscore, not a number.
  • Spaces and punctuation are not allowed. Spaces must be in double quotes.NAME="hello shell".
  • bashAll variables in are strings.
a=z                     The variable a is assigned to the string z
b="a string"            # Variable values that contain Spaces must be enclosed in quotes
c="a string and $b"     The value of a variable can refer to the value of another variable
d="\t\ta string\n"      # Variable values can use escape characters
e=$(ls -l foo.txt)      The value of a variable can be the result of a command execution
Copy the code
5.2.2 Viewing Variables

The set command displays all variables (both environment and custom), as well as all Bash functions.

 set
Copy the code

Six parameters:

6.1 Common Parameters

$n. N stands for a number. For example, the first argument passed to the script would be $1, the second would be $2, and so on… Where $0 is the name of the script. Eg: script argu.sh.

#! /bin/bash
echo "The first parameter is:The $1"
echo "The first parameter is:$2"
echo "The script name is:$0"
Copy the code

The results are as follows:

The first argument is: python the first argument is: node The name of the script is: argu.shCopy the code
6.2 Special Parameters
  • $#Passed to a script or functionSum of number of parameters.
  • $*All parameters are double""When included, all arguments are treated as one argument.
  • $@All parameters are double""When included, each positional parameter is treated as an independent parameter.
  • $?The exit status of the last command, or the return value of the function,0If the command is executed successfully, no0The command fails to be executed
  • $$The currentShellprocessID. forShellScripts, which are the processes in which these scripts resideID.
#! /bin/bash

echo "The first parameter is:The $1"
echo "The first parameter is:$2"
echo "The script name is:$0"
echo The total number of parameters accepted by the script is:$#"

curl -I baidu.com
echo "Run command status: $?"

echo "The script id is: $$"

echo 'The result of {$*} is :'The ${*}
for i in "$*"; do
    echo $i
done

echo "The result of script \$@ is:
for j in "$@"; do
    echo $j
done
Copy the code