preface

Learning Shell scripts is also to lay a foundation for compiling third-party libraries. Almost all third-party libraries need Shell syntax. If you don’t understand it, you won’t be able to compile the version you want, and you will only copy the version written by others on the network, which is actually meaningless to learn.

Let’s start by learning the basics of Shell syntax. Wait until the subsequent compilation of FFmpeg library has not understood in detail.

introduce

Shell is a program written in C language, which is a bridge for users to use Linux. Shell is both a command language and a programming language.

A Shell is an application that provides an interface through which the user accesses the services of the operating system kernel.

Ken Thompson’s SH was the first Unix Shell, and Windows Explorer was a typical graphical Shell.

Introduction to Shell

Open a text editor (you can create the file using the vi/vim command) and create a new file named test.sh with the extension sh (sh stands for shell). The extension does not affect script execution.

The first shell script

Instead, we’ll output a “Hello Word!” For example, the script code is as follows:

#! /bin/bash
echo "Hello World !"
Copy the code

Output:

#! Is a convention tag that tells the system what interpreter the script needs to execute, that is, which Shell to use.

The echo command is used to output text to a window.

Note: If no permission is displayed, run the chmod +x test.sh command to grant the permission.

variable

Variables are defined without a dollar sign ($) as follows:

my_name="DevYK"
Copy the code

Note that there can be no Spaces between variable names and equals signs, which may be different from any programming language you’re familiar with. In addition, the naming of variable names must follow the following rules:

  • The name must contain only letters, digits, and underscores (_). The first character cannot start with a number.
  • There can be no Spaces between them. Instead, use underscores (_).
  • Do not use punctuation marks.
  • You can’t use keywords in bash (see the help command for reserved keywords).

In addition to explicitly assigning a value directly, you can also assign a value to a variable declaratively, as in:

#Just remember thatfor file inThe quote after the $is not a single quote, but the key above the TAB key, or the key to the left of the 1. Otherwise it won't work.
for file in $`ls /root/android`
do
echo $file
done
Copy the code

Output effect:

Use variables:

To use a defined variable, just add a dollar sign to the name of the variable, as in:

my_name="DevYK"
echo $my_name
#Curly braces around variable names are optional, with or without them, to help the interpreter recognize the bounds of the variable
echo ${my_name} 
Copy the code

Output:

DevYK
DevYK
Copy the code

Read-only variables:

#4. Read-only variables
my_blog_url="https://www.devyk.top/"
readonly my_blog_url
my_blog_url="www.baidu.com"

Copy the code

Output:

Delete variable:

#A variable deleted cannot be used again.unsetCommand cannot delete read-only variables.Your_name =" your_name "unset your_name echo $your_nameCopy the code

Output:

You can see that after the delete variable is defined, there is no output

Variable type:

When running the shell, there are three variables:

  • 1) Local variables Local variables are defined in a script or command and are only valid in the current shell instance. Programs started by other shells cannot access local variables.
  • 2) Environment variables All programs, including those launched by the shell, have access to environment variables, and some programs need them to run properly. Shell scripts can also define environment variables if necessary.
  • 3) Shell variables Shell variables are special variables set by the shell program. Some shell variables are environment variables and some are local variables, which ensure the normal operation of the shell

string

Strings are one of the most common and useful data types in shell programming (there are few other types that are useful besides numbers and strings), and strings can be quoted in single, double, or no quotes.

#Single quotes
str='this is a book'
Copy the code

Restrictions on single-quoted strings:

  • Any character in a single quote is printed as is, and variables in a single quote string are invalid;
  • A single quotation mark cannot appear in a single quotation mark string (even with an escape character), but can appear in pairs as string concatenations.
#Double quotation marksYour_title =" Fantasy novel "STR =" Hi, what kind of novel is this? \"$your_title\" \n" echo -e $strCopy the code

Output:

Hi, what kind of novel is this? "Fantasy novels."Copy the code

Advantages of double quotes:

  • You can have variables in double quotes
  • Escape characters can appear in double quotes

Concatenation string:

your_name="DevYK_1"
#Use double quotation marks for concatenationStr1 =" $your_name" Str2 =" ${your_name}!" echo $str1 $str2#Use single quote concatenationStr3 ='1 'I'm $your_name! 'str4='1 I am ${your_name}! ' echo $str3 $str4Copy the code

Output:

2 我是 “DevYK_1” ! 2 我是 DevYK_1 !
1 我是 DevYK_1 ! 1 我是 ${your_name} !
Copy the code

Get the string length:

str_length='123456'
echo ${#str_length}
Copy the code

Output: 6

Extract string:

The following example intercepts four characters from the second character of the string:

echo ${str_length:1:4}
Copy the code

Output: 2345

Find string:

Echo 'expr index' $str_length '3' // is a backslash TAB on the leftCopy the code

Output: 3

Passing parameters

When executing a Shell script, we can pass parameters to the script in the format of $n. N is a number. 1 is the first parameter of the script, 2 is the second parameter of the script, and so on……

Example:

In the following example, we pass three arguments to the script and print them separately, where $0 is the file name of the execution:

Echo "Shell pass parameter instance!" ; Echo "execute filename: $0"; Echo "$1"; Echo "$2"; Echo "$3";Copy the code

Output:

An array of

An array can hold multiple values. Bash Shell only supports one-dimensional arrays (multidimensional arrays are not supported), and there is no need to define array sizes at initialization.

Like most programming languages, the subscripts of array elements start at 0.

Shell arrays are represented by parentheses, and elements are separated by “Spaces”. The syntax is as follows:

array_name=(value1 ... valuen)
Copy the code

Example:

${my_array[0]}" echo "${my_array[1]}" echo" ${my_array[1]}" echo" ${my_array[2]}" ${my_array[3]}"
#Use @ or * to get all the elements in the array, for example:Echo "of the array elements is: ${my_array [*]}" echo "of the array elements are: ${my_array [@]}"
#The length of an array is obtained in the same way as the length of a stringEcho "the number of array elements: ${# my_array [*]}" echo "number of array elements: ${# my_array [@]}"Copy the code

Output:

The first element is: A the second element is: B the third element is: C the fourth element is: D The elements of the array are: A B C D The elements of the array are: A B C D The number of elements of the array is: 4Copy the code

The operator

The Shell, like other programming languages, supports a variety of operators, including:

  • Arithmetic operator
  • Relational operator
  • Boolean operator
  • String operator
  • File test operator

Native Bash does not support simple math, but it can be done with other commands, such as awk and expr, with expr being the most common.

Expr is an expression calculation tool, it can be used to complete the expression evaluation operation.

Note:

  • Expressions and operators must have Spaces between them; for example, 2+2 is incorrect and must be written as 2+2, unlike most programming languages we are familiar with.
  • To include the full expression, note that this character is not the usual single quotation mark, below the Esc key.

Operator Operator:

The operator instructions For example,
+ add expr $a + $bSo that’s 30.
subtraction expr $a - $bSo that’s minus 10.
* The multiplication expr $a \* $bSo that’s 200.
/ division expr $b / $aSo that’s 2.
% Take more than expr $b % $aSo that’s 0.
= The assignment A =$b assigns the value of variable B to A.
= = The same. Use to compare two numbers, return true if they are the same. [$a == $b] returns false.
! = Is not equal. Used to compare two numbers, returning true if they are different. [$a!= $b] returns true.

[$a==$b] [$a==$b] [$a==$b] [$a==$b]

a=10 b=20 val=`expr $a + $b` echo "a + b : $val" val=`expr $a - $b` echo "a - b : $val" val=`expr $a \* $b` echo "a * b : $val" val=`expr $b / $a` echo "b / a : $val" val=`expr $b % $a` echo "b % a : If ($a == $b) then echo "a = b" fi if ($a!= $b) then echo "a = b" fi if ($a!= $b) then echo "a = b" fiCopy the code

Output:

A + b: 30 a - b: -10 a * b: 200 b/a: 2 b % a: 0Copy the code

Note:

  • A backslash () must be preceded by a multiplier (*) to perform multiplication;
  • if… then… Fi is a conditional statement, which we’ll explain later.
  • Shell expr syntax on MAC is: $((expression)), where the “*” does not need an escape symbol “”.

Relational operators:

Relational operators only support numbers, not strings, unless the value of the string is a number.

The following table lists the commonly used relational operators, assuming variable A is 10 and variable B is 20:

The operator instructions For example,
-eq Checks if two numbers are equal. Equality returns true. [$a-eq $b] returns false.
-ne Checks if two numbers are not equal. Returns true if they are not equal. [$a-ne $b] returns true.
-gt Checks if the number on the left is greater than the number on the right, and returns true if so. [$a -gt $b] Returns false.
-lt Checks if the number on the left is less than the number on the right, and returns true if so. [$a-lt $b] returns true.
-ge Checks whether the number on the left is greater than or equal to the number on the right, and returns true if so. [$a-ge $b] Returns false.
-le Checks whether the number on the left is less than or equal to the number on the right, and returns true if so. [$a -le $b] returns true.

Example:

If ($a-eq $b) then echo "$a-eq $b: "else echo "$a-eq $b: If [$a-ne $b] then echo "$a-ne $b "else echo "$a-ne $b: If [$a -gt $b] then echo "$a -gt $b: a > b" else echo "$a -gt $b: If ($a-lt $b) then echo "$a-lt $b: $a-lt $b "else echo "$a-lt $b: If ($a-ge $b) then echo "if ($a-ge $b) then echo "$a-ge $b" else echo "$a-ge $b: $a < b" fi if [$a -le $b] then echo "$a -le $b: a < b" fi if [$a -le $b] then echo "$a -le $b: A < b" else echo "$a -le $b: A > b" fiCopy the code

Output:

10-eq 20: A is not equal to b 10-NE 20: A is not equal to B 10-GT 20: A is not greater than B 10-LT 20: A is less than B 10-GE 20: A is less than B 10-LE 20: A is less than or equal to BCopy the code

Boolean operators:

The following table lists the common Boolean operators, assuming that variable A is 10 and variable B is 20:

The operator instructions For example,
! Non-operation, returns false if the expression is true, and true otherwise. False returns true.
-o Or, returns true if one of the expressions is true. [$a-lt 20 -o $b-gt 100] Returns true.
-a And, returns true if both expressions are true. [$a-lt 20 -a $b-gt 100] Returns false.
a=10 b=20 if [ $a != $b ] then echo "$a ! Else echo "$a == $b: a = b" fi if [$a-lt 100 -a $b -gt 15] then echo "$a < 100 and $b > 15: Return true" else echo "$a < 100 and $b > 15: Return false" fi if [$a-lt 100 -o $b-gt 100] then echo "$a < 100 or $b > 100: Fi if [$a -lt 5 -o $b -gt 100] then echo "$a < 5 or $b > 100: Return true" else echo "$a less than 5 or $b more than 100: return false" fiCopy the code

Output:

10! 10 is less than 100 and 20 is greater than 15. 10 is less than 100 or 20 is greater than 100. 10 is less than 5 or 20 is greater than 100Copy the code

Logical operators:

The following describes the Shell’s logical operators, assuming that variable A is 10 and variable B is 20:

The operator instructions For example,
&& The logic of the AND [[$Misplaced & a-lt 100 && $b-gt 100]] Returns false
|| The logic of the OR [[ $a -lt 100

Example:

20 if a = b = 10 [[$100 & a - lt & $b - gt 100]] then echo "return true" else echo "return false" fi if [[$a - lt 100 | | $gt - 100 b ] then echo "return true" else echo" return false" fiCopy the code

Output:

Return false Returns trueCopy the code

String operator

The following table lists the commonly used string operators, assuming that variable A is “123” and variable B is “456” :

The operator instructions For example,
= Checks if two strings are equal. Equality returns true. $a = $b returns false.
! = Checks if two strings are equal. Returns true if they are not. [$a!= $b] returns true.
-z Checks if the string length is 0, and returns true for 0. [-z $a] Returns false.
-n Checks if the string length is 0, and returns true if it is not 0. [-n “$a”] returns true.
$ Checks if the string is empty. Returns true if it is not. [$a] returns true

Example:

Str1 ="123" str2="456" if [$str1 = $str2] then echo "else echo "$str1 = $str2: If [$str1!= $str2] then echo "$str1! $str1 = str2" else echo "$str1! $str1 = str2" fi if [-z $str1] then echo "-z $str1 "else echo "-z $str1: Fi if [-n "$str1"] then echo "-n $str1: else echo "-n $str1: else echo "-n $str1: Fi if [$str1] then echo "$str1: not empty "else echo "$str1: not empty" fiCopy the code

Output:

123 = 456: STR1 does not equal str2 123! = 456: str1 is different from str2 -z 123: the string cannot contain 0. -n 123: the string cannot contain 0. 123: the string is not emptyCopy the code

File test operators:

File test operators are used to detect various properties of Unix files.

Attribute detection is described as follows:

The operator instructions For example,
-b file Checks if the file is a block device file, and returns true if it is. [-b $file] Returns false.
-c file Checks if the file is a character device file, and returns true if it is. [-c $file] Returns false.
-d file Checks if the file is a directory, and returns true if so. [-d $file] Returns false.
-f file Checks if the file is a normal file (neither a directory nor a device file) and returns true if it is. [-f $file] Returns true.
-g file Checks if the file has the SGID bit set, and returns true if so. [-g $file] Returns false.
-k file Checks whether the file is set to Sticky bits, and returns true if so. [-k $file] Returns false.
-p file Checks if the file is a named pipe, and returns true if it is. [-p $file] Returns false.
-u file Checks if the file has the SUID bit set, and returns true if so. [-u $file] Returns false.
-r file Checks whether the file is readable, and returns true if so. [-r $file] Returns true.
-w file Checks if the file is writable, and returns true if it is. [-w $file] Returns true.
-x file Checks whether the file is executable, and returns true if it is. [-x $file] returns true.
-s file Checks if the file is empty (file size greater than 0), returns true if it is not empty. [-s $file] returns true.
-e file Checks whether files (including directories) exist and returns true if so. [-e $file] Returns true.

Other checkers:

  • -s: checks whether a file is socket.
  • -l: checks whether the file exists and is a symbolic link.

Variable said the file files/root/android/shell/test. The sh, it has the RWX permissions. The following code checks the various attributes of the file:

The file = "/ root/android/shell/test. Sh" if [-r $file] then echo "file can be read" the else echo "unreadable" fi if [$file - w] then echo Fi if [-x $file] then echo "fI if [-x $file] then echo" else echo "fi if [-x $file] then echo" Fi if [-d $file] then echo else fi if [-d $file] then echo else fi if [-s $file] then echo Echo $file = fi if [-e $file] then echo $file = fiCopy the code

Output:

File Readable file writable file Executable file is a common file file is not a directory file is not empty file existsCopy the code

The echo command

The Shell’s echo directive is used to output strings. Command format:

echo string
Copy the code

example

#Display normal strings
echo "This is a book"
#You can also omit the double quotation marks
echo This is a book
#Displays escape characters
echo"\"This is a book"\"
#Show variableYour_name_2 ="DevYK_2" echo "$your_name_2#Display a newline-eBegan to escapeEcho -e "newline" \n" echo"#Display without line breaksEcho -e "not newline \c" echo" not newline"#The command execution result is displayed
echo `date`


Copy the code

Output:

This is a book This is a book" This is a book" the name of the variable is :DevYK_2 Whether a line is wrapped Or not Mon Jan 13 12:12:32 CST 2020Copy the code

Printf command

In the previous chapter, we learned the Shell echo command. In this chapter, we will learn another Shell output command, printf.

The printf command mimics the printf() program in the C library.

Printf is defined by the POSIX standard, so scripts using printf are more portable than those using Echo.

Printf uses arguments separated by reference text or space. You can use formatting strings in printf. You can specify the width of the string, the left and right alignment, and so on. By default printf does not automatically add a newline character like echo, we can manually add \n.

The syntax of the printf command:

printf  format-string  [arguments...]
Copy the code

Parameter Description:

  • Format-string: indicates the format control string
  • Arguments: Indicates the parameter list.

Example:

Printf "%-10s %-8s %-4s\n" Name Gender weight kg printf "%-10s %-8s %-4.2f\n" Guo Jing male 66.1234 printf "%-10s %-8s %-4.2f\n" Yang Guo male Printf "%-10s %-8s %-4.2f\nCopy the code

Output:

Name Gender weight kg Guo Jing male 66.12 Yang Guo male 48.65 Guo Fu female 47.99Copy the code

%s % C %d %f are format substitutes

%-10s indicates a 10 character width (- indicates left alignment, none indicates right alignment). Any character will be displayed in the 10 character width. If it is less than 10 characters, it will be automatically filled with Spaces.

%-4.2f is formatted as a decimal, where.2 is reserved for two decimal places.

The test command

The test command in the Shell is used to check whether a condition is true. It can test numeric values, characters, and files.

Numerical test:

parameter instructions
-eq Equals is true
-ne It is true if it is not
-gt Greater than is true
-ge Greater than or equal to is true
-lt Less than is true
-le Less than or equal to true

Example:

If test $[num1] -eq $[num2] then echo ' 'else echo' two numbers are not equal! ' fiCopy the code

Output:

Two numbers are equal!Copy the code

String tests:

parameter instructions
= Equals is true
! = It is true if it is not equal
Z string A string of zero length is true
– n strings A string whose length is not zero is true

Example:

Name_ ="DEVYK" name2_=" DEVYK" if test $name_ = $name2_ then echo ' 'else echo' two strings are not equal! ' fiCopy the code

Output:

Two strings are not equal!Copy the code

File test:

parameter instructions
– e file name True if the file exists
The -r filename True if the file exists and is readable
– w filename True if the file exists and is writable
– x filename True if the file exists and is executable
The -s filename True if the file exists and has at least one character
– d file name True if the file exists and is a directory
The -f filename True if the file exists and is a normal file
– c file name True if the file exists and is a character special file
– b file name True if the file exists and is block-special

Example:

If test -e./test.sh then echo ' 'else echo' file does not exist! ' fiCopy the code

Output:

File already exists!Copy the code

Process control

Unlike the Java language, sh flow control cannot be empty, for example:

if(1= =2){
  add(1.2)}else{
  // Do nothing
}
Copy the code

You can’t do this in sh/bash. If the else branch has no statement to execute, don’t write the else.

If statement syntax format:

if condition
then
    command1 
    command2
    ...
    commandN 
fi
Copy the code

Write it as a line (for terminal command prompt) :

if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
Copy the code

The for loop:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done
Copy the code

Example:

for loop in 1 2 3
do
	echo "the value is $loop"
done
Copy the code

Output:

the value is 1
the value is 2
the value is 3
Copy the code

While statement

The while loop is used to continuously execute a series of commands and also to read data from an input file; Commands are usually test conditions. The format is:

while condition
do
    command
done
Copy the code

Here is a basic while loop that tests the condition that returns true if int is less than or equal to 5. Int starts at 0 and increments by 1 each time through the loop. Run the script above, return the numbers 1 through 5, and terminate.

int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done
Copy the code

Output:

One, two, three, four, fiveCopy the code

An infinite loop

Infinite loop syntax format:

while :
do
    command
done
Copy the code

Or:

while true
do
    command
done
Copy the code

Or:

for (( ; ; ))
Copy the code

function

Linux shells can have user-defined functions that can then be called at will in shell scripts.

Shell functions are defined in the following format:

[ function ] funname [()]

{

    action;

    [return int;]

}
Copy the code

Description:

  • Function fun() can be defined with function fun() or fun() without any parameters.
  • If no, the last command will be run as the result of the return value. Return followed by the number n(0-255)

Example:

FunWithReturn (){echo "This function adds two numbers..." Echo "Enter the first digit:" read aNum echo "Enter the second digit:" read anotherNum echo "$aNum and $anotherNum! Return $(($aNum+$anotherNum))} funWithReturn echo" !"Copy the code

Output:

This function adds two input numbers... Enter the first number: 12 enter the second number: 22 the two numbers are 12 and 22 respectively! The sum of the two numbers entered is 34!Copy the code

The return value of the function is passed through the $? To obtain.

Note: All functions must be defined before use. This means that the function must be placed at the beginning of the script until it is first discovered by the shell interpreter. A function can be called using only its function name.

Function parameters:

In the Shell, arguments can be passed to a function when it is called. Inside the function body, get the value of the argument as $n, for example, $1 for the first argument, $2 for the second…

Example:

FunWithParam (){echo "First argument is $1! Echo "second parameter = $2!" Echo "$10!" Echo "${10}!" Echo "${11}!" Echo "echo"; Echo "Outputs all arguments $*! As a string. } funWithParam 1 2 3 4 5 6 7 8 9 22 11Copy the code

Output:

The first argument is 1! The second argument is 2! The tenth argument is 10! The tenth parameter is 22! The eleventh argument is 11! The total number of parameters is 11! Output all parameters as a string 1, 2, 3, 4, 5, 6, 7, 8, 9, 22, 11!Copy the code

Note that $10 does not get the tenth argument; ${10} is required to get the tenth argument. When n>=10, you need to use ${n} to get the argument.

In addition, there are several special characters used to handle arguments:

Processing parameters instructions
$# The number of arguments passed to a script or function
$* Displays all arguments passed to the script as a single string
? ID of the process in which the script is running
$! The ID of the last process to run in the background
$@ Same as $*, but used in quotes, and returns each argument in quotes.
$- 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.

conclusion

This is the introduction of the basic knowledge of Shell, the subsequent compilation of third-party libraries to write Shell scripts are unfamiliar in the introduction.

reference

  • Shell tutorial
  • Linux command