Shell Script
Script: Can execute the file, after running can implement some function (command stack, non-interactive)
Standardize the general composition of shell scripts
#! Environmental Statement (Sha-bang)
# comment Text
Executable code
#! /bin/bash #环境声明 that the script written by Bash is a program translated
I. Writing the first script program
[Email protected] ~]# vim/root/1.sh
#!/bin/bash
echo Hello World
Hostname
Cat/etc/redhat-release
Ifconfig | head-2 | Tail-1
[Email protected] ~]#/root/1.sh
Second, write for SERVER0 automatically build Yum script
[Email protected] ~]# vim/root/yum.sh #要注意排版, the contents of the Echo to the top of the line to write, echo after the ' to the same line
#!/bin/bash
rm-rf/etc/yum.repos.d/*
Echo ' [DVD]
Name=dvd
baseurl=http://172.25.254.254/content/rhel7.0/x86_64/dvd/
Enabled=1
Gpgcheck=0 ' >/etc/yum.repos.d/haha.repo
Yum Clean All
Yum Repolist
[[email protected] ~]#/root/1.sh #显示权限不够, because Vim is written in plain text, you need to give X Execute permission
-bash:/root/1.sh: Insufficient Authority
[Email protected] ~]# chmod +x/root/yum.sh
[Email protected] ~]#/root/yum.sh
Pipeline Delivery
Use | Pipeline operation
– The standard output from the previous command is given to the latter command to process
Third, redirect output
Only the correct output of the preceding command is collected, the error is displayed on the command line
2>: Only the error output of the previous command is collected, correctly displayed on the command line
&>: Collect errors from the previous command with correct output, not displayed on the command line
[Email protected] ~]# echo 123 >/opt/1.txt
[Email protected] ~]# Cat/opt/1.txt
[Email protected] ~]# cat/opt/1.txt/etc/
[Email protected] ~]# cat/opt/1.txt/etc/>/opt/a.txt
[Email protected] ~]# Cat/opt/a.txt
[Email Protected]rver0 ~]# cat/opt/1.txt/etc/2>/opt/a.txt
[Email protected] ~]# Cat/opt/a.txt
[Email protected] ~]# cat/opt/1.txt/etc/&>/opt/a.txt
[Email protected] ~]# Cat/opt/a.txt
-------------------------------------------------------------------------------------------
Iii. writing a script to create a user and set a password
[Email protected] ~]# vim/root/user.sh
#!/bin/bash
Useradd test06
Echo 123 | passwd--stdin test06
[Email protected] ~]# chmod +x/root/user.sh
[Email protected] ~]#/root/user.sh
Change the password for the user test06.
PASSWD: All the authentication tokens have been successfully updated.
To make it not display information
/dev/null #Linux黑洞设备, designed to collect not output results
[Email protected] ~]# vim/root/user.sh
#!/bin/bash
Useradd test06 &>/dev/null
Echo Test06 created successfully
Echo 123 | passwd--stdin test06 &>/dev/null
echo test06 Password Setup succeeded
[Email protected] ~]# chmod +x/root/user.sh
[Email protected] ~]#/root/user.sh
Test06 created successfully
test06 Password Setup succeeded
Variables: In order to increase the ability of the script's applicable environment, increase the flexibility of the script, convenient.
Variables: containers, with immutable names, store changed values
Variable name = changed value
Use variable: $ variable name
To reduce the difficulty of using scripts, you can create interactive
READ: Can generate interaction to assign the contents of the keyboard input to a variable
[Email protected] ~]# vim/root/user.sh
#!/bin/bash
Read-p ' Please enter the user you want to create: ' Users
Read-p ' Please enter the password you want to set: ' Pass
Useradd $user &>/dev/null
Echo $user created successfully
echo $pass | passwd--stdin $user &>/dev/null
echo $user Password Setup succeeded
[Email protected] ~]#/root/user.sh
Please enter the account number you want to create: Kobe
Please enter the password you want to set: 248
Kobe created successfully
Kobe Password Setup succeeded
-------------------------------------------------------------------------------------------
What is a variable
Values that are stored as immutable names that may vary
– Variable name = variable Value
– Easy to reuse a value with a fixed name
– Improved adaptability to mission requirements and operational environment changes
Considerations when setting a variable
– If the specified variable name already exists, it is equivalent to re-assigning a value to this variable
– Don't have spaces on both sides of the equals sign
– Variable names are made up of letters/numbers/underscores, case-sensitive
– Variable names cannot start with a number, do not use keywords and special characters
Basic format
– Reference variable Value: $ variable Name
– View variable value: Echo $ variable name, echo ${variable name}
Types of variables
Positional variables
Command-line arguments (non-interactive pass-through values) that are provided when the script is executed
$ plus numbers ($, $, $ ...): Default variables with parameters following the script file name
[Email protected] ~]# vim/root/2.sh
#!/bin/bash
echo $
Echo
echo $
Echo ${10} #显示超过两位数的值要加 {}
Echo ${11}
echo $21 #不加 {} Displays the value of the previous bit plus the next digit
[[email protected] ~]#/root/2.sh haha benniu xixi hehe lele DC TC DZ TZ 100 200
haha
Benniu
Xixi
#显示第十个值为100
#显示第十个值为200
BENNIU1 #显示第二个值加个1为benniu1
[Email protected] ~]# vim/root/3.sh
#!/bin/bash
Cat-n $ | Head-$2
[Email protected] ~]#/ROOT/3.SH/ETC/PASSWD 2
1 Root:x:0:0:root:/root:/bin/bash
2 Bin:x:1:1:bin:/bin:/sbin/nologin
pre-defined variables
The execution information used to save the script
– Use these variables directly
– You cannot assign values directly to these variables
$# The number of position variables that have been loaded
$* values for all positional variables
$? Status value after program exit, 0 indicates normal, other value is abnormal
[Email protected] ~]# vim/root/2.sh
#!/bin/bash
echo $
Echo
echo $
Echo ${10}
Echo ${11}
Echo $#
Echo $*
[[email protected] ~]#/root/2.sh 1 2 3 4 5 6 7 8 9 10 11
1
2
3
10
11
21st
#显示已加载的位置变量的个数为11
1 2 3 4 5 6 7 8 9 #显示所有位置变量的值
----------------------------------------------------------------------------------------
Operation
[[email protected] ~]# expr 10/3
[[email protected] ~]# Expr \* 3 #单独 * syntax error is displayed, front plus \ indicates multiplication sign
[[email protected] ~]# Expr 1 + 2
[[email protected] ~]# expr 3-1
[[email protected] ~]# Expr 3 #取余数 operation
$ (): Displays the output of the command in () as a parameter
[[Email protected] opt]# Date
[Email protected] opt]# date +%f #只显示年月日
[Email protected] opt]# cd/opt
[[email protected] opt]# mkdir $ (date +%f)
[[email protected] opt]# ls
2017-11-07
[Email protected] opt]# mkdir mydir-$ (date +%f)
[[email protected] opt]# ls
2017-11-07 mydir-2017-11-07
[Email protected] opt]# mkdir mariadb-$ (date +%f)
[[email protected] opt]# ls
2017-11-07 mariadb-2017-11-07 mydir-2017-11-07
[[email protected] opt]# mkdir $ (hostname)-$ (date +%f)
[[email protected] opt]# ls
2017-11-07 mydir-2017-11-07 mariadb-2017-11-07 server0.example.com-2017-11-07
-------------------------------------------------------------------------------------------
Common Test Options
Check file status
-e: Document exists as true
-D: Document exists and is directory-True
-F: Document exists and is file-true
-r: Document exists with Read permission true
-W: Document exists with Write permission true
-X: Document exists with Execute permission true
Compare integer size (with E equals two words, g means greater than, L is less than)
-GT: Greater Than
-ge: greater than or equal to
-eq: Equals
-ne: Not equal to
-LT: Less than
-le: Less than or equal to
string alignment
= =: Equal
! =: Not Equal
----------------------------------------------------------------------------------------
If single Branch statement
If [condition test]; Then #[] There must be a space.
Command sequence XX
Else
Command Sequence yy
Fi
[Email protected]/]# vim/root/5.sh
#!/bin/bash
If [$1-eq $];then
echo Hello
Else
echo Hi
Fi
[Email protected]/]#/root/5.sh 1 1
Hello
[Email protected]/]#/root/5.sh 1 2
Hi
Please write a script:
The user enters an IP address (read), determines whether it can communicate with the IP address, general output "IP OK" otherwise output "IP No"
[Email protected]/]# vim/root/6.sh
#!/bin/bash
Read-p ' Please enter an IP address: ' IP #变量为ip
Ping-c 2 $ip &>/dev/null
If [$?-eq 0];then
Echo ${ip} OK
Else
Echo ${ip} No
Fi
[Email protected]/]#/root/6.sh
Please enter an IP address: 127.0.0.1
127.0.0.1 OK
[Email protected] ~]#/root/6.sh
Please enter an IP address: 1.1.1.1
1.1.1.1 No
-----------------------------------------------------------------------------------------
If multi-branch statement
If [condition test 1]; Then
Command sequence XX
elif [condition Test 2]; Then
Command Sequence yy
Else
Command Sequence ZZ
Fi
Score greater than or equal to 90 excellent
Greater than or equal to 80 good
Greater than or equal to 70 pass
Greater than or equal to 60 still requires effort
60 below in the cattle of Chopin, also can not play the elder brother Sadness
[Email protected] ~]# vim/root/8.sh
#!/bin/bash
Read-p ' Please enter your score: ' num
If [$num-gt];then #大于100分
Echo score is wrong
elif [$num-lt 0];then #小于0分
Echo score is wrong
elif [$num-ge];then
Echo Excellent
elif [$num-ge];then
echo Good
elif [$num-ge];then
Echo Pass.
elif [$num-ge];then
Echo still needs to work hard
Else
echo in the Ox Chopin, also can not play the elder brother Sadness
Fi
-----------------------------------------------------------------------------------------
Create a/root/foo.sh script on Server0
1) When running/root/foo.sh Redhat, the output is Fedora
2) When running/root/foo.sh fedora, output is Redhat
3) when no parameters or parameters are not redhat or
When fedora, its error output produces the following information:
/root/foo.sh Redhat|fedora
": The output of all special characters as normal text characters
[Email protected] ~]# vim/root/foo.sh
#!/bin/bash
if [= = = Redhat];then
echo Fedora
elif [= = = Fedora];then
Echo Redhat
Else
Echo '/root/foo.sh Redhat|fedora '
Fi
[Email protected] ~]#/root/foo.sh Redhat
[Email protected] ~]#/root/foo.sh Fedora
[Email protected] ~]#/root/foo.sh haha
#!/bin/bash
If [$#-eq 0];then #表示脚本文件后位置变量的个数为0时, that is, there are no parameters (no input parameters)
Echo '/root/foo.sh Redhat|fedora '
elif [= = Redhat];then
echo Fedora
elif [= = = Fedora];then
Echo Redhat
Else
Echo '/root/foo.sh Redhat|fedora '
Fi
"": You can Change "no" to "null"
#!/bin/bash
If ["$" = = Redhat];then
echo Fedora
elif ["$" = = Fedora];then
Echo Redhat
Else
Echo '/root/foo.sh Redhat|fedora ' >&2 #将正确输出变成错误
Exit 2 #脚本退出返回值, that is, the last line of the command is a echo$? Displays a value not specified as 0 2
Fi
-------------------------------------------------------------------------------------------
For loop structure
Loop structure: The repeated execution of the statement, loop to execute
For variable name in value list
Do
Command sequence
Done
[Email protected]/]# vim/root/for.sh
#!/bin/bash
For a in 1 2 3 4 5
Do
Useradd nsd$a
Echo Nsd$a created successfully
Done
[Email protected]/]# vim/root/for02.sh
#!/bin/bash
For a in 1 2 3 4 5
Do
echo Hello
Done
-------------------------------------------------------------------------------------------
Case 5: Write a bulk Add user script
Create a/root/batchusers script on Server0
1) This script requires a user name list file as a parameter
2) If no parameters are provided, this script should give a hint
Usage:/root/batchusers, exit and return the corresponding value
3) If a nonexistent file is provided, this script should give a
Show Input file not found, exit and return the corresponding value
4) New User login Shell is/bin/false, no need to set password
5) User list test file:
Http://classroom/pub/materials/userlist
# wgethttp://classroom/pub/materials/userlist
[Email protected]/]# vim/root/batchusers
#!/bin/bash
If [$#-eq 0];then
Echo ' Usage:/root/batchusers ' >&2
Exit 1
Fi
if [!-e $];then #! Indicates that there is no
Echo ' Input file not found ' >&2
Exit 2
Fi
For a in $ (cat $)
Do
Useradd-s/bin/false $a
Echo $a created successfully
Done
-----------------------------------------------------------------------------------------
#!/bin/bash
If [$#-eq 0];then
Echo ' Usage:/root/batchusers ' >&2
Exit 1
Fi
If [-E $];then
For a in $ (cat $)
Do
Useradd-s/bin/false $a
Echo $a created successfully
Done
Else
Echo ' Input file not found ' >&2
Exit 2
Fi
Linux Learning Notes-engineer technology: Shell Scripting Basics