Shell Script Basics (i)

Source: Internet
Author: User
Tags chmod

With the more and more application of Linux system in enterprise, the automatic management of server becomes more and more important, in some complex Linux maintenance work, a lot of repetitive output and interactive operation are not only time consuming and error-prone, so shell script can be processed in batch, Automate a series of maintenance tasks, greatly reducing the burden on administrators.

First, Shell scripting basics
1, write the first shell script
1), Vim first.sh
[[email protected] ~]# Mkdir/shell//Create a Shell directory
[Email protected] ~]# vim first.sh//new first. SH file
#!/bin/bash
cd/boot/
Pwd
LS-LH VML
2), set execute permissions and execute
[[email protected]/]# chmod +x first.sh//Add executable permission
[[email protected]/]#./first.sh//Run script file directly
/boot
-rwxr-xr-x. 1 root root 4.0M 11?. Vmlinuz-2.6.32-431.el6.x86_64
[Email protected]/]#
2. Annotate scripts, friendly output, easier to read
1)
[Email protected] ~]# vim first.sh
~
#!/bin/bash
#this is my first shell-scipt
Cd/boot
echo "The current directory is located in:"
Pwd
echo "The files that begin with VML include:"
LS-LH VML

2), execute./first.sh following
[Email protected] ~]#./first.sh
The current directory is located at:
/boot
Files that begin with VML include the following:
-rwxr-xr-x. 1 root root 4.0M 11?. Vmlinuz-2.6.32-431.el6.x86_64
[Email protected] ~]#
3, redirect operation
In Linux maintenance, you can change the direction of the input and output content instead of using the default standard output, output device (keyboard and monitor), which becomes "redirected."
1),> indicates that the redirected output,>> indicates a redirect append
[[email protected] ~]# uname-p > Kernel.txt//Save the current host's CPU type information to the Kernel.txt file
[email protected] ~]# cat Kernel.txt
x86_64
[[email protected] ~]# uname-r >> kernel.txt//Append kernel version to kernel.txt file
[email protected] ~]# cat Kernel.txt
x86_64
2.6.32-431.el6.x86_64
[Email protected] ~]#
2), redirect input,< indicates redirect input
[[email protected] ~]# vim pass.txt//Add initial Password string content "123456"
[[email protected] ~]# Useradd Chenpeng//Add user "Chenepng"
[Email protected] ~]# passwd--stdin Chenpeng < pass.txt
Take the password from the Pass.txt file
Changing password for user Chenpeng.
Passwd:all authentication tokens updated successfully.
3), error redirection, can be used to collect error messages executed by the program, to provide a basis for troubleshooting, for example: Do the following to save the error message that occurs when you use the TAR command backup to the Error.log file
[Email protected] ~]# tar kcf/noendir/etc/.tgz/etc/2> error.log
[email protected] ~]# cat Error.log
Tar:/noendir/etc/.tgz: No. Open: No file or directory
Tar:error isn't recoverable:exiting now
4) The &> operator can save two types of output information to the same file, for example, in the automation script that compiles the source package, to ignore the process information of the Make,make install operation, you can direct it to an empty file/dev/null
First download the HTTPD software to this machine, then perform the Vim httpd_install.sh and enter the following:
[Email protected] ~]# vim httpd_install.sh
#!/bin/bash
cd/usr/src/httpd-2.2.17/
./configure--prefix=/usr/local/httpd--enable-so &>/dev/null
Make &>/dev/null
Make install &>/dev/null
Set Permissions chmod +x httpd_install.sh
Final execution./httpd_install.sh (note/front point)
4. Pipeline operation
Example: When using the grep command to query a user name using/bin/bash as the shell, the entire line of content that matches the condition is output, which can be further filtered by combining pipeline operations with the awk command, outputting only the user name and login shell columns.
1) Normal effects prior to extraction
[[email protected]/]# grep "/bin/bash$"/etc/passwd
Root:x:0:0:root:/root:/bin/bash
Jerry:x:500:500::/home/jerry:/bin/bash
Chenpeng:x:501:501::/home/chenpeng:/bin/bash
2) effect after extraction, only show user name and Shell column
[[email protected]/]# grep "/bin/bash$"/etc/passwd | Awk-f: ' {print $1,$7} '
Root/bin/bash
Jerry/bin/bash
Chenpeng/bin/bash
3) Again for example: Displays the percentage of disk that has been used, and can do the following, where DF, Grep,awk command and pipeline operations are used
[Email protected]/]# Df-ht | grep "/$" | awk ' {print $6} '
11%
Second, use shell variables
1. Custom variables: Valid only in your own shell environment
1) Define new variables and reference variables
The variable operations in bash are relatively straightforward and not as complex as other high-level programming languages such as C/c++,java. When defining a new variable, it is generally not necessary to declare it in advance, but to specify the variable name directly and give the initial value (content).
The basic format for defining variables is "variable value = variable Value", and there are no spaces on either side of the equals sign. The name of the variable must begin with a letter or underscore, and the name should not contain special characters such as + 、—、,/,.%, &, #,)
For example, to define a variable named "Product" (with a value of Benet) and a variable named "Version" (a value of 5.0), and to view the value of a reference variable, perform the operation:
[Email protected]/]# product=benet
[Email protected]/]# version=5.0
[Email protected]/]# echo $product
Benet
[Email protected]/]# echo $product $version
Benet 5.0
2, special operation of variable assignment
1) The function of double quotation marks: When the content of the assignment contains spaces, for example:
[[email protected]/]# benet=benet 5.0//Wrong assignment
-bash:5.0:command not found
[[email protected]/]# benet= "Benet 5.0"//Correct assignment
[Email protected]/]# echo $benet
Benet 5.0
Within the double quotation mark range, use the "$" symbol to refer to other variable values
[[email protected]/]# accp= "ACCP $Version"//Assign value with variable value
[Email protected]/]# version=4.0
[Email protected]/]# echo $ACCP
ACCP 4.0
3) Anti-apostrophe ()的作用:用于将某个命令的输出结果赋值给变量,例如:<br/>[[email protected] /]# ls -lhWhich Useradd '
-rwxr-x---. 1 root root 101K 12?. 8 2011/usr/sbin/useradd
4) $ () function: Can replace the anti-apostrophe, solve the nesting problem, because the anti-apostrophe can not be nested, for example: Query the package that provides the USERADD command program installed configuration file location.
[[email protected]/]# RPM-QC $ (RPM-QF $ (which useradd))
/etc/default/useradd
/etc/login.defs
5) The function of the Read command: to prompt the user for information such as:
[email protected]/]# Read Todir1
/opt/backup/
[Email protected]/]# echo $todir 1
/opt/backup/
[[email protected]/]# read-p "Please specify the backup directory:" Todir2
Please specify a backup storage directory:/opt/backup
[Email protected]/]# echo $todir 2
/opt/backup
3, set the scope of the variable
The newly defined variables are valid only in the current shell, and if you want to enter a new shell environment, you will need to export the variables as "global variables" using the Export command.
[Email protected]/]# echo "$product $version"
Benet 4.0
[Email protected]/]# Export product version
[Email protected]/]# bash
[Email protected]/]# echo "$product $version"
Benet 4.0
You can also assign a value to a variable while exporting the global variable, for example:
[Email protected]/]# export web= "www.google.com"
[Email protected]/]# echo $web
www.google.com
4, the operation of the numeric variable
Several commonly used operators:
+: Addition calculation
-: Subtraction Calculation
*: Multiplication calculation, note can not only use "
"Symbol, otherwise it will be treated as a file wildcard.
/: Division Calculation
%: Modulo operation, also known as the take-up operation, is used to calculate the remainder after the numerical value together
Examples are as follows:
[Email protected]/]# x=35
[Email protected]/]# y=16
[Email protected]/]# expr $x + $y
51
[Email protected]/]# expr $x-$y
19
[Email protected]/]# expr $x * $y
560
[Email protected]/]# expr $x/$y
2
[Email protected]/]# expr $x% $y
3
To assign the result of an operation to another variable, you can combine the command substitution operation (using a backslash), for example, to calculate the 3-square of Y, and assign the result to Ycube
[Email protected]/]# ycube=expr $y \* $y \* $y
[Email protected]/]# echo $ycube
4096
Third, special shell variables
1. Environment variables
Environment variable system is installed, there is no need to create, can be used directly, we first look at:
[[Email protected]/]# env
Hostname=localhost.localdomain
version=4.0
Selinux_role_requested=
Term=xterm
Shell=/bin/bash
..................
We can add the script directly to the $path search path, so we don't have to use it when we execute the script.
[Email protected] ~]# Cd/shell
[[email protected] shell]# ls
first.sh
[[email protected] shell]# first.sh//Command not found direct execution
-bash:first.sh:command not found
[[email protected] shell]# path= "$PATH:/shell"//Add//root to the search path
[[email protected] shell]# echo $PATH//view modified search Path
/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/shell
[[email protected] shell]# first.sh//Run script directly with file name
The current directory is located at:
/boot
Files that begin with VML include
-rwxr-xr-x. 1 root root 4.0M 11?. Vmlinuz-2.6.32-431.el6.x86_64
The global configuration file for the environment variable is/etc/profile, for all users, for example: Change the history command bar number to 200, only for the root user
[Email protected] ~]# Vim/root/.bash_profile
...//Omit part of the content
Export histsize=200//need to add
Just add the last line above, and then execute the source/root/.bash_profile to make it effective.
[[email protected] ~]# source/root/.bash_profile//Read and execute the settings in the file
[Email protected] ~]# history | Wc-l//Modified history command hop count
110
2, position variables, such as the number of two and
[Email protected] ~]# vim adder2num.sh
#!/bin/bash
sum=expr $1 + $2
echo "$ + $ = $sum"
[Email protected]/]#./adder2num.sh 1 1
1 + 1 = 2
3, pre-defined variables, the system is installed after the, can not be created, can only use, for example: $ #表示命令行中位置参数的个数, $Represents the contents of all positional parameters, $? Represents the return state after the previous command was executed, and returns 0 for correct. $ A represents the name of the currently executing script or program.
Example: Making a backup data script
[Email protected]/]# vim mybak.sh
#!/bin/bash
tarfile=beifen- date +$s . tgz
Tar zcf $tarfile $
&>/dev/null
echo "Executed $ script"
echo "Complete a backup of $# objects altogether"
echo "Specific content includes: $"
Executes the script./mybak.sh, back up two files
[Email protected]/]#./mybak.sh/etc/passwd/etc/shadow
The./mybak,.sh script has been executed,
A total of 2 object backups completed
Specifically:/etc/passwd/etc/shadow
View Backup Results
[Email protected]/]# LS-LH beifen-

-rw-r--r--1 root root 3.4k 23:29 beifen-1401972022.tgz
-rw-r--r--1 root root 3.4k 23:29 beifen-1401972038.tgz

Shell Script Basics (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.