The shell is the user interface of the Linux operating system, and we often need to write scripts to allow the operating system to automate the requirements of a series of instructions, this article will briefly describe the language features required to develop the shell script.
A shell script is an instruction sequence whose instructions can be executed directly in the terminal. Similarly, instructions in the terminal can be written to the script.
The script file is typically .sh
used as the suffix name, and the first line #!
specifies the program that executes the script at the beginning:
#!/usr/bin/bash
#!
the first line to begin with is called Hashbang or shebang. #
This is the line comment character in the shell script.
There are typically three ways to execute scripts:
sh start.sh
: Creates a SH child process execution script in the terminal, and the performer needs to have read access to the script.
This method actually passes the script path as a parameter to the sh
command.
source start.sh
: Executing the script in the terminal is equivalent to copying the instructions from the script to the terminal execution.
Local variables in the script will remain in the terminal environment variable, and the environment such as the PID and working directory of the script is consistent with the terminal.
./start.sh
: Executes the script in the child process according to the program specified by Hashbang.
sh
command has some useful options to help us develop and debug scripts:
sh -n start.sh
: syntax checking of scripts, no actual script execution
sh -x start.sh
: Outputs the command to be executed to the stderr for easy debugging
Variable
The variables in the shell are weakly typed, and the variable names can contain only letters, numbers, or underscores "_", and the first character can only be letters.
The shell is primarily text-oriented rather than data-based, so the default type of the variable is string.
A=abcecho$A
Variables need not be declared before they are used, and =
spaces cannot be added around when assigning values to variables.
A = abc
will be interpreted by the shell as an execution instruction A
, with parameters of =
and abc
.
$
As a variable marker, the echo $A
instruction displays the contents of the variable a abc
, which can be written in order to explicitly specify the variable name ${A}
.
A=aAB=abecho${A}B
$(cmd)
You can use the output of the command as a return value, such as:
PWD=$(pwd)
The variable $PWD
stores the current working directory path.
Strings can be written directly in the shell, but it is still recommended to identify the strings in single or double quotation marks.
The string that is identified in single quotation marks is $
not used as the variable identifier, and the double quotation marks are replaced with the $
variable contents.
A="abc"echo‘$A‘# $Aecho"$A"# abc
String concatenation does not require any operators, just write them together:
A="abc"B="123"echo"$A+$B" # abc+123echo"$A$B" # abc123echo"$Adef" # abcdef
Global variables
Variables can be divided into local variables and global variables by scope, the variables defined in the previous example are local variables, and scopes are limited to the process that executes the script.
A child process can inherit global variables from a parent process, and export
directives are used to define global variables:
export A=abc
Integer variable
The shell supports only integer calculations, and declare
commands can declare integer variables, which are let
used for arithmetic operations:
declarea=1let a=a+1echo$a # 2let a+=1echo$a # 3
let
The instruction supports arithmetic operators including:
+
: addition
-
: Subtraction
*
: multiplication
/
: Division
**
: exponentiation
%
: Take Surplus
let
The instruction also supports arithmetic assignment operators for arithmetic operators, such as +=
.
Array
In bash, you can use parentheses to define an array, separating elements with spaces, and array subscripts starting with 1:
arr=(‘a‘"abc")echo${arr[1]}
You can also define an array directly using the subscript:
arr2[1]=1arr2[2]=2
The method can also be used to modify an existing array.
Special variables
Some special variables are pre-defined in the shell that allow you to obtain environmental information:
$$
: The process ID (PID) of the execution script
$?
: The return value of the previous command
$!
: ID of the execution process of the previous background instruction
The above variables are equally valid in the interactive terminal.
There are also variables to get the arguments passed in when the script is executed:
$0
: The file name of the script
$1
~ $n
: The nth parameter passed to the script
$#
: Number of parameters passed in
[email protected]
: Parameter list
$*
: A list of arguments in a single string form
Process Control if
declarea=90if [$a-gt 80 ]then echo"A"elif [$a-lt 60 ]then echo"C"else echo"D"fi
The end flag fi
is if
anti-write, and we will encounter this naming style of bash elsewhere.
Note that []
the space next to it must not be omitted.
-lt
-gt
for the size comparison of an integral type:
-eq
: Equals (equal)
-ne
: Not equal to (not equal)
-gt
: Greater than (greater)
-ge
: Greater than or equal to (greater-equal)
-lt
: smaller than (less)
-le
: Less than or equal to (less-equal)
Making complex logic judgments is also simple:
if [$a-gt-a$a$a eq 91 ) ]then echo"make no sense"fi
The logic operation follows the principle of short circuit calculation.
<
, >
such as operators can []
only be used for string comparisons in, and in [[]]
, to <
>
size comparisons of integers and strings, &&
and to use and ||
to write logical expressions.
If the condition judgment is not necessarily used []
or [[]]
an expression, it can be any command. The return value of the command is 0 if the If judgment is true, and the non 0 is false.
[]
and [[]]
escape expressions can also be executed like a normal instruction, which returns 0 if true, and false returns a value other than 0.
[-gt-a-lt 4 ]&&echo‘ok‘
In addition, if there are more kinds of conditions to judge:
Judging string equality
if [${NAME}=‘tmp‘ ]then echo"name is tmp"fi
Determine if a file exists
if [-e tmp ]then echo"tmp exists"fi
Determine tmp
if it exists, tmp
can be a directory or a file.
Determine if the file is normal
if [-f tmp ]then echo"file tmp exists"fi
Determines whether it is a tmp
file, tmp
not a directory.
Determine if the directory
if [-d tmp ]then echo"directory tmp exists"fi
Determine if you have Execute permissions
if [-x tmp ]then echo"tmp is executable"fi
Does not determine whether the file can be executed, only the permission is determined x
. Therefore, TMP is also judged to be true if it is a directory with X permissions.
Similarly, -w
determine if you have write permission to -r
determine whether you have Read permissions.
Determine if the file is empty
if [-s tmp ]then echo"file is not empty"fi
Case
Case is similar to a switch statement in another language:
case${NAME} in ‘a‘) echo"name is a" ;; ‘b‘) echo"name is b" ;; *) echo"other names" ;;esac
Starting with the first matching tag, there must be between the two tags ;;
, which *)
are the default labels when the other labels do not match.
For
A For loop can traverse a sequence:
fori$(seq 1 10);do echo$idone# echo: 1 2 3 ... 10
The output of some commands can also be used as a sequence:
fori$(ls);do echo$idone
Traverse All Parameters:
forarg"[email protected]";do echo$arg done
Another form of A For loop:
for (( i=0; i<100; i++)); do echo $idone
While
declarei=0while [$i-lt 10 ]do echo$i i=$i+1done
while(true)
Such a cycle of death is also easy:
declarei=0whiledo echo$i [!$i-lt 10 ]&&break i=$i+1done
Function
The shell provides the function that defines the function, which is like a sub-script in the script:
range(){ for(( i=0; i<${1}; i++))do echo$i done return${1}}range 100
The function also uses the positional parameter $1
~ $n
to access the parameter, which is the name of the $0
function, [email protected]
and the $#
meaning of the variable is unchanged.
Inter-process communication pipeline
The pipeline is used to input the output of the previous instruction as the next instruction:
ls|grep".zip"
Xargs
Some directives do not support the use of pipes to pass parameters, so commands are required xargs
find|xargs
Xargs separates the input into parameters with a space delimiter, and then passes the arguments to LS.
redirect
Redirects are used to redirect the input and output of a command from a standard stream to a file. The standard flow includes:
- stdin: Standard input stream, file descriptor 0
- STDOUT: Standard output stream, file descriptor 1
- STDERR: Standard error stream, file descriptor 2
Output to a file, overwriting the original content:
echo"hello">
Output to file, append to end of file:
echo"hello">> 1.txt
Input from File:
wc< 1.txt
REDIRECT standard error output stream:
cmd2> 2.txt
Append the standard error output to the file:
cmd2>> 2.txt
REDIRECT standard errors and standard output to a file together:
cmd>2>&1
2>&1
is to redirect stderr to stdout.
Background execution
The shell can return immediately after executing a single line of instructions, and $?
the ID of the executing process can be obtained by the variable when returned:
sleep&[1echo$!79403
Shell and script