1.1 Shell Script Writing specification
1.2 Variable and special variable application
1.3 Local variables and global variables
1.4 Test-piece expression
------------------------------------------------------
Background: In some complex Linux maintenance work, a lot of repetitive inputs and interactions are laborious and error-prone.
The benefits of scripting:
Batch processing, automated completion of maintenance, reduce the burden of administrators.
The Linux shell script is a special kind of application
There are a number of common shell interpreters
Different shell interpreter internal directives are used
/bin/bash is the default shell interpreter in most Linux.
All subsequent scripts are written in a bash script
See what shell interpreters are available on our system?
Command: Chsh–l or Cat/etc/shells
1. Write the first shell script
A shell script is a collection of the commands we normally execute into a file, which is then given the file execution permission to execute once.
Linux systems do not differentiate files with file suffix names, but for ease of memory and management, we habitually end the script file with. sh
Vim first.sh
Then, save exit!!! (at the time of programming, our first program is usually Hello world! , here we also as an example)
Explain:
First line: #!/bin/bash
Specifies that the interpreter running this script is/bin/bash
#表示这一行是注释, and then followed one! Represents this non-comment!!! Praise
Line second to third: Comment information, indicating the function of this script
When writing a larger script, if there is no good comment, then no one will be able to understand the meaning of it
Line four: implementation of scripting Features! (Enter commands that you normally enter in the shell)
How the script executes: (five types)
1, add executable permissions to the file, and then use the absolute path to execute
chmod +x first.sh
/root/first.sh
2, add executable permissions to the file, and then use relative path to execute--->./start
./first.sh
3. Execute with SH command
SH first.sh
[Email protected] ~]# sh--help
GNU Bash, version 4.2.46 (1)-release-(X86_64-REDHAT-LINUX-GNU)
Usage:sh [GNU long option] [option] ...
SH [GNU long option] [option] script-file ...
GNU Long options:
--debug
--debugger
--dump-po-strings
--dump-strings
--help
--init-file
--login
--noediting
--noprofile
--norc
--posix
--protected
--rcfile
--rpm-requires
--restricted
--verbose
--version
Shell options:
-IRSD or-c Command Or-o shopt_option (invocation only)
-ABEFHKMNPTUVXBCHP or-o option
Type ' sh-c ' "help set" ' For more information about shell options.
Type ' Sh-c help ' For more information about shell builtin commands.
[Email protected] ~]# sh-c Help
GNU Bash, version 4.2.46 (1)-release (X86_64-REDHAT-LINUX-GNU)
These shell commands is defined internally. Type ' help ' to see the This list.
Type ' help-name ' to-find out more about the function ' name '.
Use ' Info Bash ' to find out more about the shell in general.
Use the ' man-k ' or ' info ' to the Find out more about the commands not in the this list.
A Star (*) next to a name means, the command is disabled.
Job_spec [&] history [-c] [-D offset] [n] or hist>
((expression)) if COMMANDS; Then COMMANDS; [Elif c>
. filename [arguments] jobs [-LNPRS] [jobspec ...] or jobs >
: Kill [-S Sigspec |-n Signum |-sigs>
[Arg ...] Let Arg [arg ...]
[[expression]] local [option] name[=value] ...
alias [-P] [Name[=value] ...] Logout [n]
BG [Job_spec ...] Mapfile [-N Count] [-O origin] [-s c>
Bind [-lpvspvs] [-M keymap] [-F filen> popd [-n] [+n |-n]
Break [n] printf [-v var] format [arguments]
Builtin [Shell-builtin [Arg ...] pushd [-n] [+n |-n | dir]
caller [expr] pwd [-LP]
Case WORD in [PATTERN [| PATTERN] ...) > read [-ers] [-a array] [-D Delim] [->
CD [-l|[ -P [-e]] [dir] Readarray [-N Count] [-O origin] [-s>
command [-PVV] command [arg ...] readonly [-AAF] [Name[=value] ...] o>
Compgen [-ABCDEFGJKSUV] [-o-option] > return [n]
complete [-ABCDEFGJKSUV] [-PR] [-de] > select NAME [in WORDS ...;] do comm>
compopt [-o|+o option] [-de] [name: > Set [-ABEFHKMNPTUVXBCHP] [-O option->
Continue [n] shift [n]
Coproc [NAME] command [redirections] shopt [-PQSU] [-o] [optname ...]
declare [-aaffgilrtux] [-p] [name[=va> source filename [arguments]
dirs [-CLPV] [+n] [-n] suspend [-f]
Disown [-h] [-ar] [Jobspec ...] Test [expr]
echo [-nee] [arg ...] Time [-P] Pipeline
Enable [-A] [-dnps] [-f filename] [na> times
eval [arg ...] Trap [-LP] [[ARG] signal_spec ...]
exec [-CL] [-a name] [command [argume> True
Exit [n] Type [-AFPTP] name [name ...]
Export [-FN] [name[=value] ...] or ex> typeset [-aaffgilrtux] [-p] name[=va>
False Ulimit [-SHACDEFILMNPQRSTUVX] [limit>
FC [-E ename] [-LNR] [first] [last] o> umask [-P] [-S] [mode]
FG [JOB_SPEC] unalias [-a] name [name ...]
For NAME [in WORDS ...]; Do command> unset [-f] [-v] [name ...]
for (EXP1; exp2; exp3); Do comman> until COMMANDS; Do COMMANDS; Done
function name {COMMANDS;} or Name > Variables-names and Meanings of so>
getopts optstring name [arg] wait [ID]
hash [-LR] [-P pathname] [-DT] [name > while COMMANDS; doing COMMANDS; done
Help [-DMS] [pattern ...] {COMMANDS;}
4, use. [FileName] Execution Note: There is a space behind the point
. first.sh
5. Use the source command to execute the note: The General source command is used to execute the configuration file
SOURCE first.sh
Note: The first two types require files with executable permissions (in the enterprise, deprecated, unsafe)
The following three types, do not need to have executable permissions (recommended use)
-------------------------------------------------------
2.SHELL variables
Definition: A space where a variable value can be stored
By default: Each shell can be viewed as a different execution environment in Linux, so the same variable name, variable values are different in different execution environments
2.1 Categories of variables: custom variables, environment variables, positional variables, pre-defined variables
output of 2.2 variables:echo $[variable name] # $ is a special character that references a variable (fixed format)
2.3 Description of variables: ( Note that the shell is case sensitive )
2.3.1 Custom variables: users define their own variables according to their own environment, (the simplest variable)
Declaration format: Variable name = variable Value
Note: The left and right sides do not have spaces;
Variable names can only start with letters and underscores, and special symbols cannot appear in names
Special symbols: +-*/,. ' \?%*, etc.
Example: 1, defining variables and outputting
2. Call two variables together
3. Use of {}
Read command, copy to variable, via file or standard input
Read $xg $xiaogan
[Email protected] ~]# read-p "Input your password:" passwd
[[email protected] ~]# read-s-P "Input Your password:" passwd #-s option does not echo
Scope of the variable:
In general, the variables we define are only available in the current shell and cannot be used when in a different shell.
We can use the Export command to declare these variables as global variables so that they can still be used in the new shell:
Export Xiaogan XG
Set is used to display local variables
env to display environment variables
Export to display and set environment variables
Difference:
Set displays variables for the current shell, including variables for the current user
ENV displays the current user's variables
Export Displays the shell variables currently exported as user variables
Operation of Numeric variables
The numerical operation of the shell script is used in the process control of the script program (such as number of cycles, usage comparison, etc.)
In a shell environment, only simple integer operations can be performed
There must be a space between the operator and the variable,
The operation of integers is mainly done by the internal command expr command.
Usage: Variable 1 operator variable 2
Where variable 1, variable 2 ... The corresponding number of numeric variables that need to be computed (requires a $ symbol call) are commonly used by several operators as shown below
Addition Operation: +
Subtraction Operations:-
Multiplication: \* #由于 * There is another meaning, so you need to escape with a backslash
Division Operation:/
Modulus (take rest) operation:%
2.3.2 Environment variables:
environment variable is a class of variables that are created in advance by the Linux system, which is necessary for the operation of the system itself.
Mainly used for the user's work environment, including (user's host directory home, command lookup path, the user's current directory pwd, login terminal shell, etc.) the value of the environment variable is maintained by the operating system itself, and changes as the user's state changes
Env Tune Current environment variable
Configuration file for environment variables in/etc/profile (global)
User host directory/home/zhangsan/.bash_profile (local)
PWD #pwd命令就是调用了这个变量才能进行输出
PATH
Define the default search path for a command
We are talking about the MySQL executable program optimization When we write the program path directly to the variable can be entered in any directory.
USER
SHELL
HOME
Put the script we wrote in $path's default search path.
1. Writes the/root directory to the environment variable in path, but it is not permanently active
2. Refresh the/etc/profile configuration file to be permanently active
3. The executable program under/root can be executed directly under any directory without any command to execute.
Note: In order to facilitate the running of the current directory executable file, so I put. (current directory)---> is also added to the PATH variable
2.3.3 Position Variable:
When you perform a command-line operation, the first field represents the command word or program name,
The remaining string parameters are assigned the position variable in order from left to right
Positional variables, also known as positional parameters, use $ $ ... $9
Example: Ls–a/root
Where LS indicates that the command word-A is the positional parameter $1/root is the positional parameter,
Vim sum.sh
Sh–x sum.sh 110 112
2.3.4 Pre-defined variables:
$#: Number of positional variables in the command line (the program executes several positional parameters)
$*: The contents of all positional variables (specific content such as/boot is a specific content)
$?: The state returned after the previous command was executed, when the return status value is 0 indicates normal execution, and a value other than 0 indicates an exception or error
Determine if an error occurs correctly for 0 exception error for non 0 value between 1-127
$: The currently executing process/program name (which is the name of the currently executing command or program)
!$: last parameter named above
[Email protected] ~]# sh backup.sh/root/boot
2.3.5 Single quotes:
The content to be assigned includes "$", "\", and so on,
When special characters with other meanings are used, enclose them in single quotation marks;
No other value can be referenced within the range of single quotes, any word nonspacing as a normal character,
However, the contents of the assignment contain single quotes that need to be escaped with the \ ' symbol to avoid collisions.
2.3.6 double quotes:
1. When a space is assigned to the right of the = sign, use double quotation marks to enlarge it
2, in the range of double quotation marks can also refer to other variables, so that the existing variable can be assigned to the new variable
2.3.7 Reverse apostrophe: value, same as $ ()
The anti-apostrophe must be an executable command within the range. Otherwise there will be an error
When nesting occurs, the anti-apostrophe is not very good, which is we will choose to use the $ () value symbol
-------------------------------------------------------
Conditional expressions
1. Use test command to judge
2. Use the [] command
Usage:test conditional expression
usage:[conditional expression]
1. File test
File testing refers to a given path name, determine whether it is a file or directory, the judge has read and write execution permissions, determine the existence of the file directory
The common options are as follows
-D: Test whether the directory or directory exists
-E: Test whether the directory or file exists (Exist)
-F: Test whether the file or file exists
-R: Tests whether the current user has permission to read (read)
-W: Tests whether the current user has permission to write (write)
-X: Tests whether the current user has permission to execute (excute)
Example: generally we hang on the CD-ROM when used to mount the CD in the/media/cdrom directory, but the RHEL system does not exist by default this directory, we can first determine whether this directory exists
We use [] this way to judge, this is also the most commonly used in a format note that you need at least one space on each side
Use Echo to output a $? You can see that the return value is not 0 by judging the return result we can conclude that the CDROM directory does not exist.
When I have cdrom this directory is created after the judgment is the condition of the return value of 0 this expression is established.
By looking at the variable $? method is not intuitive we can use & in logic test to judge
Perform a double & after an expression
Output Yes if the previous expression is true or nothing
[Email protected] ~]# [-d/media/cdrom]
BASH: [-d:command not found ...
[Email protected] ~]# [-d/media/cdrom]
[[email protected] ~]# echo $?
1
[Email protected] ~]# test-d/media/cdrom
[[email protected] ~]# echo $?
1
[Email protected] ~]# Mkdir/media/cdrom
[Email protected] ~]# [-d/media/cdrom]
[[email protected] ~]# echo $?
0
[[Email protected] ~]# [-d/media/cdrom] && echo "Yes" Yes
[Email protected] ~]# Rm-rf/medis/cdrom
[Email protected] ~]# Rm-rf/media/cdrom
[[Email protected] ~]# [-d/media/cdrom] && echo "YES"
[Email protected] ~]#
Basics of 1-22-shell Scripts