The concept of the Shell is derived from the Unix command interpreter. The Shell not only interprets the commands entered by the user, but also interprets the scripting language used to execute commands. Shell scripts can improve the efficiency of user operations and system management.

Write a script

Basic elements of the shell

  • #! /bin/bash Mandatory, specifying the type of shell
  • # comments. In the shell, comments are written after #, and nothing after # is executed
  • variable
  • Control loop branch

Special symbols in the shell

symbol role
#! Specify the shell used to execute the script
$ Instead of a backslash escape, use the plain character that follows as the variable name, such as $a, to indicate the value of variable A. If the variable contains more than one character, use {} to enclose the variable
Echo ‘my $SHELL’ echo ‘my $SHELL’
For the contents in quotation marks, except for the special functions of $, escape character \, and inverted quotation mark ‘, all the other characters are ordinary characters.
` The string in quotes is interpreted as a shell command line (the same function can also be used with $()), and the result replaces the entire backquote section.
\ Backslashes are escape characters that turn special characters into ordinary characters. Using a backslash (\) before a character prevents the shell from interpreting subsequent characters as special characters.
* The value contains 0 or more special characters. Example yum.* can also be yum. A, yum. Ab, yum
? Represents any character. Example yum.? It can be yum. A yum. B yum. C, but be careful that there must be any character after the decimal point
[] Represents any one of the brackets. [abcdef] can be any of the letters a, B, C, D, e, or F. [-] represents a range, and [a-z] represents any letter from a to Z. [^]^ [^ ABC] [^ ABC] [^ ABC] [^ ABC] [^ ABC] [^ ABC] [^ ABC
The $() You can assign a command replacement output to a variable
{} The required strings can be generated by parenthesis extension, which can contain contiguous sequences containing a starting point and an ending point, or multiple items separated by commas
user@computer: ~$echo {a,b,c} a b c user@computer: ~$echo user{1,5,8} user1 user5 user8 user@computer: ~$ echo {0.. 10} 0 1 2 3 4 5 6 7 8 9 10 user@computer: ~$mkdir {dir1,dir2,dir3} user@computer: ~$ls -- ld dir{1,2,3}Copy the code

variable

Shell variables can hold pathnames, file names, a number, and so on. Divided into three categories:

  • Local variables: (Local variables) are used only in the Shell in which they were created, and can be used and modified arbitrarily within the Shell program.
  • Environment variables: They can be used in the Shell that created them and in any subroutine derived from them. Some variables are user-created, others are proprietary (PATH, HOME). They are part of the system environment and can be used in shell programs without having to define them. You can also modify it in the shell.
  • Internal variables: provided by the system. Unlike environment variables, users cannot modify them.

The local variable

Local variables are used in scripts for the user’s current shell lifetime

Considerations for using local variables
  1. There can be no Spaces on either side of the equal sign
  2. The value contains Spaces and must be enclosed in double quotation marks
  3. Shell variables can be case sensitive and can be written in upper and lower case letters
  4. Variables are weakly typed and do not declare a type
Variable declaration and assignment formats
Variable = value (no Spaces on equal sign)Copy the code
Variable reference
$variable name ${variable name} Recommended use method 1 if the variable name contains one character. Recommended use Method 2 If the variable name contains more than one character. Example: $a ${ABC}Copy the code
Remove the variable
user@computer: ~$name=Jack user@computer: ~$echo ${name} user@computer: ~$unset name #Copy the code
Setting read-only variables
If you do not want to change the value of a variable, you can set it as a read-only variable. Variable name = value ReadOnly Variable nameCopy the code

The environment variable

Bash presets a number of environment variables that, in practice, you can call directly. Environment variables can be used for all subroutines, including editors, scripts, and applications

Built-in environment variables
variable meaning
HOME Represents the user directory. CD ~ to the user’s home directory or use the CD can be directly back to the user’s directory.
SHELL Which SHELL program is currently used in this environment? For bash, the default is /bin/bash
PWD The path to the user’s current working directory, indicating where the user is currently in the Linux file system
HISTSIZE This withhistoryCommands can be recorded by the system, and the “number” of records is set by this value.
PATH Directories are separated by colons (:). Files are searched in order by directories in the variable PATH, so the order of directories is also important.
Environment variables precautions
  • Environment variables can be set on the command line, but these values are lost when the user logs out
  • Environment variables are capitalized
  • It must be exported using the export command
Setting environment Variables
Variable-name =value export variable-nameCopy the code
Display environment variables
Env can see all environment variables echo $environment variable name (display a variable)Copy the code
Clearing environment variables
Unset Specifies the name of the environment variableCopy the code
Modify the PATH environment variable
Modify the PATH environment variable so that the script can be executed by directly entering the name of the file without adding the PATH. Mysql > alter environment variables; Mkdir shdir && CD shdir vi hello chmod 755 hello CD ~ export PATH=$PATH:$HOME/shdir In any directory, enter Hello to execute the file. If the environment variables are incorrectly modified, you can restore the default values after you log in to the system again after exit.Copy the code
Modify environment variables in the configuration file
You need to know which profiles environment variables are associated with: Different distributions have different names, but the names are common: find / -name "*profile" find / -name "*bashrc" Global profile /etc/profile Local profile ~/.bashrcCopy the code

Internal variables

Internal variables are a special type of variable provided by Linux that is used in programs to make judgments. The values of these variables cannot be changed in shell programs.

Partial internal variables
variable meaning
$# The number of positional arguments passed to the shell program
$? The completion code of the last command or shell program executed inside the shell program (return value)
$0 The name of the shell program
$* A single string of all arguments passed when the shell program is called, “Parameter 1″,” parameter 2″… Form saves parameters
$@ “Parameter 1″,” parameter 2″… Form saves parameters
$n The NTH argument
? PID of this program
$! PID of the previous command

Input and output

The input

-n NCHARS read n characters -p PROMPT display a PROMPT -r cancel transfer -s quiet mode, -t TIMEOUT will not prompt you if the specified time is exceeded. Read will stop automaticallyCopy the code

The output

Echo [options] String common options -n does not wrap at the end -e enables the conversion of backslash control characters -e does not handle escape characters. This is the default option;Copy the code
#! /bin/bash
# Enter a sentence, print the input words
read -p 'please type some words, I will print them: ' words
echo $words
Copy the code

Conditions for testing

Test conditional expression

# test The test command returns 0 if the test condition is true, otherwise a non-0 numeric test statement is returned along with the if/ THEN and case statements to form the control transfer structure of shell programmingCopy the code

[] Conditional expression

If the value of the conditional expression is true, it returns zero. If it is false, it returns a non-zero valueCopy the code

File status judgment

Conditional statements True or false
-d filename Return true if filename is a directory file
-f filename If the file exists and is a normal file, true is returned
-r filename Return true if filename is readable
-s filename Return true if the length of filename is greater than 0
-w filename Return true if filename is writable
-x filename Return true if filename is executable
-e filename Whether the file exists
#! Read -p 'input file path: 'file if [-e $file] then echo' exists' else echo 'does not exist' fiCopy the code

Conditional statements

if
if[conditional expression];thenCommand sequencefi"Conditional expression"Is executed when the test value of"Sequence of commands"Otherwise, the command following the conditional statement is executed. Conditional expressions andthenThe semicolon between";"Acts as a command separator.Copy the code
if-else
if[Conditional expression]thenCommand Sequence 1elseCommand Sequence 2fi"Conditional expression"Is executed when the test value of"Command Sequence 1"Otherwise, execute the command"Command Sequence 2". There can be one or more commands in a command sequence.Copy the code
if-elif-else
if testConditional expression 1thenCommand Sequence 1elif[Conditional expression 2]thenCommand Sequence 2elseCommand Sequence 3fiThis is a conditional statement containing two levels of nesting, when"Conditional expression 1"If true, the command is executed"Command Sequence 1"Otherwise, in"Condition table reached formula 2"If true, execute"Command Sequence 2"Otherwise, execute the command"Command Sequence 3"."Command Sequence 3"Is part of the second clause statement.Copy the code
Application, for example,
#! /bin/bash # Read -p 'Please input the file path: ' file if [ -d $file ] then echo 'this is a directory' elif [ -f $file ] then echo 'this is a file' else echo 'wrong file type, or the file do not exist' fiCopy the code

Numeric operator

The operator meaning
N1 – eq n2 Determine whether n1 and n2 are equal. If they are, return 0; otherwise, return 1
N1 n2 – can be Check whether numbers n1 and n2 are not equal. If they are not, return 0; otherwise, return 1
N1 – lt n2 Determine whether the number n1 is less than n2, if, return 0, otherwise return 1
N1 – gt n2 Determine whether the number n1 is greater than n2, if, return 0, otherwise return 1
N1 – le n2 Determine whether the number n1 is less than or equal to n2, if, return 0, otherwise, return 1
N1 – ge n2 Determine whether the number n1 is greater than or equal to n2, if, return 0, otherwise, return 1

String operator

The operator meaning
string Return true if the string string is not empty
-n string Return true if the string length is greater than 0
-z string If the string length is 0, true is returned
string1 = string2 Return true if the strings string1 and string2 are equal
string1 ! = string2 Return true if the strings string1 and string2 are unequal

Logical operator

The operator meaning
E1 – a e2 Returns 0 if both the logical expressions e1 and e2 are true, and 1 otherwise
E1 – o e2 Returns 0 if either of the logical expressions E1 and e2 is true, and 1 otherwise
! e1 Returns 0 if the logical expression E1 is not true, and 1 otherwise

Looping statements

Python-style for loops

For variable name in parameter list do command list done Assigns each element in the parameter list to the variable name. After each assignment, execute the command list. Parameter List indicates the range of variable namesCopy the code

C style for loop

For ((initializes a variable value; End loop condition; Do command sequence doneCopy the code

while

While [conditional expression] do command list done The loop executes the commands in the command list until the value of the conditional expression is false.Copy the code

until

Until [condition] do sequence Done Until the condition is met the loop endsCopy the code

Application, for example,

#! /bin/bash # rename all.txt files in the specified directory to *.doc directory=$1 if [!  $directory ] then echo "please input the argument directory" exit fi files=`ls ${directory}` for file in $files; do if [ -f ${file} ] echo $file then suffix=${file#*\.} echo $suffix if [[ $suffix == "txt" ]] then prefix=${file%\.*} mv $directory/$file $directory/$prefix.doc fi fi doneCopy the code

function

Functionname () {command list return} functions can be called as: functionname argumentsCopy the code