Fundamentals of Shell Scripting
Writing specifications for 1.shell scripts
2 variable and special variable application
3 Local variables and global variables
4 Test-judgment expression
In some complex Linux maintenance efforts, a large number of repetitive input and interaction operations 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 lot of common shell interpreter there are many kinds of shell-time internal command prompt method, there are some differences, can be viewed through the/etc/shells file
[Email protected] ~]# Cat/etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
/usr/sbin/nologin
/bin/tcsh
/bin/csh
/bin/bash is the default shell interpreter in most Linux. All subsequent scripts are written in a bash script
Writing the first shell script
Put the order of the usual operations command into the file to give execute permission, once the execution
Let's write the first script frist.sh
Linux does not prefix the file, for the convenience of memory here I will end with. Sh
[email protected] 1607]# cat firsh.sh
#!/bin/bash
#This is my first shell scripts
Comments:
#! /bin/bash is mostly about declaring that all I write is the bash language (I'm using bash interpreter)
Second behavior Comment Line, comment information does not take effect
When writing a larger script, if there is no good comment, then no one will be able to understand the meaning of it
Commands to be executed in the future
Different ways to execute scripts
The first uses absolute path execution
The second method of using relative paths, such as./
The third use of the SH command to execute the format SH script name does not require EXECUTE permission
The fourth kind uses. (space) The way the script name executes does not require EXECUTE permission. a.sh
Fifth use of source script name does not require EXECUTE permission
Recommended use after three kinds, in the production environment do not easily give the file executable permissions;
Next, let's explore what's important in the script---variables
A variable is defined as a space that can hold a variable value
Can be changed in different environments is a variable value
Common shell variables are custom variables, environment variables, positional variables, pre-defined variables
Typically use the Echo output variable name format =$ variable name
echo $? echo $ variable Name
1. Custom variables
Custom variables are variables that users define themselves according to their own environment
A simple variable in bash, instead of declaring it in advance, assigns the variable name directly and assigns it to the initial value;
The basic format for defining variables is variable name = variable value equals two times no spaces are allowed;
Variable names can only be preceded by a letter and an underscore name cannot contain +,-*,/. , 、 ? % * ...... And so on some special characters
Example:
To define a variable named Linux with a value of 7.2 (note case)
[Email protected] 1607]# linux=7.2
[Email protected] 1607]# echo $Linux
7.2
[Email protected] 1607]# linux=7.0
[Email protected] 1607]# echo $linux
7.0
Can be defined directly at the command line, the above is to define a variable and give the value, through the ECHO output variable $ is a special character of the reference variable (must use the $ symbol)
There must be a space between echo and the variable being called
Example 2:
When you need to call two sets of variables together
[Email protected] 1607]# echo $Linux $linux
7.2 7.0
Use echo directly after the variable called with $ if there are multiple spaces separated by
Example 3:
You should use {} to enclose the variable name when the variable name and subsequent characters are easily confused
[Email protected] 1607]# echo ${linux}system
7.2system
[Email protected] 1607]# echo ${linux}system
7.0system
Variable values There are some other special operations
Double quotation marks (")
When a space is assigned to the right of the = sign, you need to use double quotation marks to expand it
[Email protected] ~]# version= "rehdat9.0"
[Email protected] ~]# echo $version
Rehdat 9.0
You can also reference other variables within the range of double quotes, allowing you to assign existing variables to the new variable
[Email protected] ~]# linux=7.2
[Email protected] ~]# system= "Rhel$linux"
[Email protected] ~]# echo $system
RHEL 7.2
Single quotation mark (')
When the content to be assigned includes "$", "\", and so on, special characters with other meanings,
You should enclose it in single quotation marks.
Other values cannot be referenced within the single quotation mark range, any word nonspacing as a normal character, but the contents of the assignment contain single quotes that need to be escaped with the \ ' symbol to avoid collisions
Anti-apostrophe (')
Press the key below the keyboard ESC.
The inverse apostrophe is primarily used for command substitution, allowing the output of a command's screen to be assigned to a variable.
The anti-apostrophe must be an executable command within the range. Otherwise there will be an error
Example:
To find detailed information about a program on the command line
[Email protected] 1607]# rpm-qf ' which pwd '
Coreutils-8.22-11.el7.x86_64
[[email protected] 1607]# RPM-QF $ (which pwd)
Coreutils-8.22-11.el7.x86_64
It is important to note that it is difficult to use a backslash to implement a nested command in a command, which can be $ () in place of the anti-apostrophe
[Email protected] 1607]# rpm-q ' rpm-qf ' Whichls '
Rpm:no arguments given for query
Which-2.20-7.el7.x86_64
Package LS isn't installed
[[email protected] 1607]# Rpm-q $ (RPM-QF $ (whichpwd))
Coreutils-8.22-11.el7.x86_64
4) Read command
In addition to the above assignment you can use the Read command to assign values, the Read command is used to prompt the user to enter information, so as to achieve a simple interactive process (in fact, we entered the command is an interactive process)
You need to read a line from the standard input device keyboard and use a space as a delimiter when executing
For example, I define two variable operations as follows
[[email protected] shell]# Read Kernel system
3.10 7.2
[Email protected] shell]# echo $kernel
3.10
[Email protected] shell]# echo $system
7.2
For more interactive images, improve ease of use, plus the-p option to set the cue message
[Email protected] shell]# read-p "inputyour Password:" passwd
Input your password:123456
[Email protected] shell]# echo $passwd
123456
Our actions are only valid in the current bash environment, and will not be valid for other consoles or other shel.
We go into the shell of the current shells
[Email protected] shell]# echo $Linux
7.2
[[email protected] shell]# bash into the child shell
[Email protected] shell]# echo $Linux
[Email protected] shell]# exit #exit退出当前的bash回到父bash
Exit
[Email protected] shell]# echo $Linux
7.2
Variables that are locally defined after entering the child shell will not take effect. It can only be explained that there are no output variables in the current bash
View all current variables by set
View global variables with env
[[Email protected] shell]# env
xdg_session_id=72
hostname=rhel7.2
Selinux_role_requested=
Term=xterm
Shell=/bin/bash
histsize=1000
ssh_client=192.168.137.1 61008 22
Selinux_use_current_range=
ssh_tty=/dev/pts/0
User=root
Change a local variable to a global variable
[Email protected] shell]# export City=shengzheng #设置为 global variables
[Email protected] shell]# bash #进入子shell
[Email protected] shell]# echo $city
Shengzheng
It is important to note that the names of the variables are strictly case-sensitive
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 an empty space between the operator and the variable. The operation of integers is mainly done by the internal command expr command.
Format 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 Operation: \*
Division Operation:/
Modulus (take rest) operation:%
[Email protected] shell]# a=100
[Email protected] shell]# b=200
[Email protected] shell]# expr $A + $B
100+200
[Email protected] shell]# expr $A + $B
300
[Email protected] shell]# expr $A-$B
-100
[Email protected] shell]# expr $A \* $B
20000
[Email protected] shell]# expr $A * $B
Expr:syntax Error
[Email protected] shell]# expr $A/$B
0
[Email protected] shell]# expr $A% $B
100
To assign the result of an operation to another variable, you can do this.
[[email protected] shell]# a=$ (expr $A + $B)
[Email protected] shell]# echo $A
300
The custom variable is here
Environment variables:
An environment variable is a class of variables that the system itself runs that needs to be created in advance by the Linux system.
Mainly used for the user's working environment, including (user's host directory, command lookup path, user's current directory, login terminal, etc.) the value of environment variable is maintained by the operating system itself, change with the user's state change
Env Tune Current environment variable
[[Email protected] shell]# env
xdg_session_id=72
hostname=rhel7.2
Selinux_role_requested=
Shell=/bin/bash
Term=xterm
histsize=1000
ssh_client=192.168.137.1 61008 22
Selinux_use_current_range=
ssh_tty=/dev/pts/0
User=root
Configuration file for environment variables in/etc/profile (global)
User host directory/home/zhangsan/.bash_profile (local)
$PWD
The PWD command calls this variable in order to output.
[Email protected] shell]# echo $PWD
/root/shell
[Email protected] shell]# Cd/home
[Email protected] home]# echo $PWD
/home
$PATH
Define the default search path for the 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.
[Email protected] shell]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
$USER
[Email protected] shell]# echo $USER
Root
[Email protected] shell]# Su-andy
Last Login:fri 5 21:18:30 CST in PTS/2
[Email protected] ~]$ echo $USER
Andy
$SHELL
[Email protected] shell]# echo $SHELL
/bin/bash
$HOME
[Email protected] shell]# echo $SHELL
/bin/bash
[Email protected] shell]# echo $HOME
/root
[Email protected] shell]# Su-andy
Last Login:tue 21:35:02 CST onpts/0
[Email protected] ~]$ echo $HOME
/home/andy
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
[Email protected] shell]# pwd
/root/shell
[[email protected] shell]# path= "$PATH:/root/shell"
[Email protected] shell]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/shell
[Email protected] shell]#./first_shell.sh
Hello World
[Email protected] shell]#
2. Refresh the/etc/profile configuration file to be permanently active
[Email protected] shell]# Vim/etc/profile
3. The executable program under/root can be executed directly under any directory without any command to execute.
[Email protected] shell]#./first_shell.sh
Hello World
[Email protected] shell]# first_shell.sh
Hello World
2. Position variable
In order to use shell scripting: it is convenient to provide the parameter bash by the command-action program The concept of positional variables is referenced.
When you perform a command-line operation, the first field represents the command word or program name, and the remaining string parameters assign a value to the position variable in order from left to right
Positional variables also become positional parameters, using $ ... $9
Taking ls-lh/boot/as an example
where all but LS are positional parameters.
-LH is a positional parameter that uses the $ = to go back to the back row (space delimited)
$ A is a predefined variable instead of a positional variable
3. 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)
[email protected] shell]# cat shell.sh
#!/bin/bash
sum=$ (expr + $)
echo "$ + $ = $SUM"
[[Email protected] shell]# sh shell.sh 1 2
1 + 2 = 3
We use an example to explain
Vim backup.sh compiles a package of multiple directories or files using the package command
[Email protected]]# cat backup.sh
#!/bin/bash
file=back-$ (date +%s). tar.gz
Tar zcf $file $* &>/tmp/tar.log
echo "executed a $ A script"
echo "total $ #个备份对象 Completed"
echo "Specific content includes $*"
[Email protected] shell]# sh backup.sh/root/shell//boot
Executed a backup.sh script
Complete 2 backup objects in a total
Specific content includes/root/shell//boot
One is to use the test command to judge the other is the [] command
Test condition expression
[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)
Where the-e option is to determine whether the file or directory, this option is not very common,
Because when you want to judge the file, you specify a directory in which there is a subdirectory with the name of the file you want to judge, so it will return 0, so it is not very common.
If you determine whether a directory or file exists, you only need to use-D or-F to judge it.
The option for the next three test permissions is to test whether the specified file or directory has permission to read and write execution
After executing the test condition pass the predefined variable $? You can test the return status of a command to determine if there is a
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
[Email protected] shell]# [-D/MNT]
[[email protected] shell]# echo $?
0
[Email protected] shell]# ls/mnt
Addons Isolinux Repodata
EFI LiveOS Rpm-gpg-key-redhat-beta
EULA Media.repo Rpm-gpg-key-redhat-release
GPL Packages TRANS. TBL
Images Release-notes
[[email protected] shell]# echo $?
0
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.
[Email protected] shell]# Mkdir/media/cdrom
[Email protected] shell]# [-d/media/cdrom/]
[[email protected] shell]# echo $?
0
When I make CDROM this directory is created after the decision is made conditional return value is 0
This expression is set up.
By looking at the variable $? method is not intuitive we can use & in logic test to judge
[[Email protected] shell]# [-d/media/cdrom/]&& echo "YES"
YES
[[Email protected] shell]# [-d/media/cd/]&& echo "YES"
[[email protected] shell]# echo $?
1
Perform a double & after an expression
Output Yes if the previous expression is true or nothing
Logic Test we'll talk later.
The above is the content of the file test, which we will use when we write the script.
It is critical that the script is executed to see the results of the judgment.
This article is from the "Technical Achievement Dream" blog, please be sure to keep this source http://andyliu.blog.51cto.com/518879/1844545
Fundamentals of shell Scripts 1