Author of this article: Eternity has no limit

background

Recently, the team needed to write a shell script for the front-end incremental module packaging, mainly to solve the problem that it takes a long time to complete the package each time. We can determine which modules need to be packaged according to git submission. In order to realize this requirement, we have to learn some common shell commands as front-end cutters.

preface

The basic idea of learning a language is the same, just as we learn javascript, we should know what shell has, such as variables, parameter passing, operators, flow control, functions, file inclusion and so on. Next, I will share one by one according to the knowledge learned this time.

variable

In shell, we also need to define variables as we write javascript, so what are the rules in shell variable definition? I have listed the following points:

  • The name must contain only letters, digits, and underscores (_), and cannot start with a digit
  • There can be no Spaces between them. Instead, use the underscore _
  • Do not use punctuation marks
  • Can’t use reserved words in bash (you can use help to view reserved words)

Here’s an example:

Conforms to the rule variable
SHELL
A_B_C_D
_abcd
abc123

Invalid variable name? var=123 var*name=hwjyCopy the code

${SHELL} ${SHELL} ${SHELL} ${SHELL} ${SHELL} ${SHELL} ${SHELL} ${SHELL} With that in mind, let’s take a look at this chestnut:

for lang in Ada Coffe Action Java; do
    echo "I am a $langScript engineer"
done
Copy the code

If the lang variable is not curly braced, the program will recognize the langScript as a variable. This will not result in the expected result. To avoid this situation, we need to use curly braces when using the variable. It is good coding practice to help the interpreter recognize variable boundaries.

Parameter passing

When we execute Shell scripts, we need to pass some initialization parameters to Shell scripts. For example, the script I write this time must pass in the git branch name to let the program know which branch package I use and which version I need to upload to the platform, for example:

Let’s start by writing a simple Shell script

#! /bin/bash
# test.sh

echo "The first parameter is zero$0";
echo "The second parameter is zeroThe $1";
echo "The third parameter is zero$2";

Copy the code

Then set executable permissions to the script and execute the script

chmod +x test.sh 
./test.sh hello word

# Execution resultThe first parameter is./test.sh the second parameter is Hello and the third parameter is wordCopy the code

Now, some of you might not understand why I only pass in two parameters, but I actually get three parameters. The reason is that $0 defaults to the file name of the execution and contains the file path. Let’s take a look at some other special characters that are commonly used to handle arguments. Here’s a list of them:

Parameter processing character instructions
# $ The number of arguments passed to the script
$* Displays all arguments passed to the script as a single string. Such as”
With” “, in order to *” cases in brackets (“), by”
1
2… 2…
Output all arguments in n”.
$$ ID of the process in which the script is running
$! The ID of the last process to run in the background
$@ with
Same, but used in quotes, and returns each argument in quotes. Such as * Same, but used in quotes, and returns each argument in quotes. Such as”
@” @”, “@”
1 1″ ”
2 “… Print all arguments as “$n”.
$- Displays the current options used by the Shell, as does the set command.
$? Displays the exit status of the last command. 0 indicates no errors, and any other value indicates an error.

The operator

There are always some operations in any language, but what operators are included in the Shell? In the process of Shell script writing, it is found that the commonly used operators are relational operators, Boolean operators, string operators, arithmetic operators, in addition to the file test operators.

Here are a few things to be aware of when using operators, for example:

Chestnut one:

#! /bin/bash
value=`expr 1 + 1`
echo "The sum of the two numbers is:${value}"
Note that there is a space between the expression and the operator, and that the full expression is contained within it.
Copy the code

Chestnut 2:

#error
[${a}= =${b}]

#success
[ ${a}= =${b} ]

The expression must be placed between square brackets with Spaces, otherwise an error will be reported.
Copy the code

If else process control

Flow control is often encountered in a Shell script. For example, in the writing of this script, it is necessary to determine whether the current submitted code has been changed to which corresponding App and collect them. Finally, a packaging queue is generated to make each App into a complete front-end package.

The flow control in the Shell is a little different from the way we used to write JavaScript. The difference is that the flow control in the Shell cannot be null, which means that you should not write the else flow if there is no statement to execute.

Common flow control syntax is as follows:

#! /bin/bash

# if statement
if condition
then
    command
fi

# if else statement
if condition
then
    commandIf
else
    commandElse
fi

# if else-if else statement
if conditionIf
then
    commandIf
elif conditionElif
then
    commandElif
else
    commandElse
fi

# for loop statement
for lang in js html css
do
    echo ${lang}
done

# while loop statement
while condition
do
    command
done
Copy the code

function

In script writing, it is often involved in the encapsulation of a common method into a function, so what is the function definition in Shell script? Let’s first look at a function definition format:

#! /bin/bash

[ function ] funname [()]
{
    action;
    [returnint; ] }Copy the code

Here we can find that the Shell function definition is not very different from the javascript function we usually write. Basically, we are writing javascript functions should have the same thing in Shell.

Therefore, on the definition of the function, we will not go to repeat, since we can find some commonalities in the definition of the function, so the call of the function should be about the same. Here we simply define a function and call it, can be straightforward understanding.

#! /bin/bash

function fun() {echoThe $1$2
}

fun hello world

Copy the code

This is a good example of how to use a function as an argument, but it is important to note that the function does not get an unlimited $1 $2 parameter… ${10} = ${10}; ${10} = ${10};

File contains

How do we understand file inclusion in the Shell? We can imagine wrapping common code, functions and methods as a separate file, just as we often do with Mixins when we write Vue. In this script, the installation, package compilation, and upload to the management platform are all common operations, so the use of file inclusion here fits the usage scenario.

Shell files contain the following syntax:

#! /bin/bash

. path/filename # notice the dot (.) There is a space between the and pathorsource path/filename
Copy the code

It is a good practice to make our scripts flexible in the form of file inclusion, so that we can use relevant function methods anytime and anywhere.

Other commands

  • Echo string output
#! /bin/bash

# Display a normal string
echo "hello world"

# Display escape characters
echo "\"hello world\"" # "Hello world"

# display variable
content="hello world"
echo "He said ${content}"

# show line breaks
echo -e "hello \n" # -e turns on the escape, that is, \n can be newline
echo "world"

Redirect the result to the file
echo "hello world > test"
Copy the code
  • exit [code]

Exit the current process with the exit code

  • rm [options] name…
#! /bin/bash

The # rm parameter has the following parameters
# -i Interactive query when deleting files
# -f Forcible deletion
# -r Recursively deletes all listed directories and their subdirectories
# -v displays the processing
We usually use -rf
rm -rf /* Delete all directory files from the root directory
Copy the code
  • cp [options] source dest
#! /bin/bash

The # cp parameters are as follows
# -a This option is usually used when copying directories, preserving links, file attributes, and copying everything under the directory. The action is equal to the dpR parameter combination
# -d Preserve links when copying. The links in question are equivalent to shortcuts in Windows.
# -f overwrites existing target files without prompting.
# -r If the source file is a directory file, all subdirectories and files under this directory will be copied.
We usually use -r
cp -r /opt/ /newopt/
Copy the code
  • cd
#! /bin/bash

# 跳到 /home/aaa/
cd /home/aaa

# Jump to your home directory
cd ~

# jump two levels above the current directory
cd ../..

Copy the code
  • ls
#! /bin/bash

List all directories in the current directory
ls /

List all files in the current directory whose names start with test
ls -ltr test*

List all directories containing file details under /home
ls -lR /home

Copy the code

conclusion

In the preparation of Shell script and reinforce the relevant Shell knowledge. For students don’t often write a Shell script command, my personal experience is, seize the interoperability of language, generality, can quickly learn a new language, actually both languages, the front frame, to have such thinking, does not face completely written things felt so strange, so do not know how to start. Always believe that all roads lead to Rome.