当前位置:网站首页>2020-09_ Shell Programming Notes
2020-09_ Shell Programming Notes
2022-07-03 12:16:00 【jackaroo2020】
Chapter one Shell Script programming application guide
1. Study Shell The foundation of programming .
- vi/vim To use skillfully
- Linux Skilled use of common commands
- common Linux Network service deployment troubleshooting
2. Shell Introduction to the concept and principle of script .
shell Is a command interpreter . It's on the outer layer of the operating system , Be responsible for direct dialogue with users , Explain user input to the operating system , And handle the output of various operating systems , Output to screen return to user .
3. Simple and complex shell Script .
Example 1. eliminate /var/log Under the message Simple command script for log file .
# Put all the commands in one file and pile them up to form a script .
# To use root Identity to run the script
# Clear log script
cd /var/log
cat /dev/null > messages
echo "Logs cleaned up."
# Tips :/var/log/messages Is the log file of the system , Very important
problem :
(1) No root Can't clean up the log .
(2) There are no process control statements , In short, sequential operation , There is no success in judgment and logicality .
Example 2. Include command 、 Clearing variables and process control statements /var/log Under the messages Of the log file shell Script .
#!/bin/bash
# Clear log script
LOG_DIR=/var/log
ROOT_UID=0 # $UID by 0 When , Only users have root User's rights
# To use root User to run , Brackets are separated by spaces
if [ "$UID" -ne "$ROOT_UID" ]
then
echo "Must be root ro tun this script."
exit 1
fi
cd $LOG_DIR || {
echo "Cannot change to necessary directory." >&2
exit 1
}
cat /dev/null > messages && echo "Logs cleaned up."
exit 0
# Return before exiting 0 Indicates successful return 1 It means failure
Expand : Three ways to empty the log and file contents :
[[email protected] day1]# echo >test.log # There is a blank line
[[email protected] day1]# > test.log # Redirect
[[email protected] day1]# cat /dev/null > test.log
4. Linux The default script interpreter of the system ?
Centos linux By default shell yes bash.
Check the method :echo $SHELL or grep root /etc/passwd
5. shell Script creation and execution
- At the beginning of the script ( first line )
A standard shell The first line of the script will indicate which program ( Interpreter ) To execute the contents of the script , stay linux bash Programming is generally :
#!/bin/bash
or
#!bin/sh < ==255 Within characters
“#!” Also known as magic number , When executing a script , The kernel will be based on "#!" The latter interpreter determines which program should be used to interpret the contents of the script . Be careful : This line must be the first line at the top of each script .
sh by bash The soft links .
If python, Then the first behavior , The execution is as follows :python test.py perform
#!/usr/bin/env python
6. shell Basic norms and habits of script development
(1) Start by specifying the script interpreter
#!bin/sh or #!/bin/bash
(2) Add copyright and other information at the beginning
#Date: 16:29 2020-3-30
#Author: Created by oldboy
#Mail: [email protected]
#Function: This scripts function is....
#Version: 1.1
Tips : Configurable vim The above information is automatically added when editing the file , The way is to modify ~/.vimrc The configuration file .
(3) The script does not need Chinese comments
Try to use English notes to prevent the trouble of Chinese garbled code after this machine or switching the system environment .
(4) Script to .sh Extension name
(5) Excellent code writing habits
I. The paired symbol contents are written at one time , Prevent omission , Such as :{},[],’’,""
II. [] There should be spaces at both ends of brackets , When writing, you can leave a space [ ]
III. Process control statements are written at one time , Adding content , Such as :
if The statement format is completed at one time :
if Condition content
then
Content
fi
for Cycle format completed at one time :
for
do
Content
done
(6) Make the code readable by indentation
Chapter two Shell Variable basis and depth
1. environment variable
Environment variables are used to define Shell Operating environment , Guarantee Shell Correct execution of commands . Home directory .bash_profile File or global configuration /etc/bashrc,/etc/profile,/etc/profile.d In the definition of .
Login shows that the loaded content can be placed in /etc/profile.d Under the table of contents .
Traditionally , All environment variables are capitalized . Before the environment variable is applied to the user process , Must use export Command export .
use evn or set Show default environment variables .unset Eliminate local variables and environment variables .
2. local variable
I. Ordinary string variable definition :
Variable name =value; Variable name =‘value’; Variable name =’'value"
II. Command variables :
Variable name =``; Variable name =$()
habit : Numbers are not quoted , Other default double quotes .
Single quotation marks : What you see will be output .
Double quotes : Output everything in double quotation marks , If there is an order in the content , Variable , Special escape , The command result will be parsed first , And then output the final content .
No quotes : Generally continuous string , Numbers i, The path, etc. can be without quotation marks . However, it is best to replace it with double quotation marks .
3. Special variables
I. Positional variable
$0 Gets the currently executed shell The filename of the script , Include script path , Such as
dirname $0 # File path
basename $0 # File name
n a take When front Of board That's ok Of s h e l l foot Ben Of The first n individual ginseng Count value , n = 1..9 , When n by 0 when surface in foot Ben Of writing Pieces of name , Such as fruit n Big On 9 , be n Gets the currently executed shell The first part of the script n Parameter values ,n=1..9, When n by 0 Is the file name of the script , If n Greater than 9, be n a take When front Of board That's ok Of shell foot Ben Of The first n individual ginseng Count value ,n=1..9, When n by 0 when surface in foot Ben Of writing Pieces of name , Such as fruit n Big On 9, be {10}
$# Get current shell The total number of parameters in the script command line
Enterprise case : Control the number of parameters transmitted by the user
[ $# -ne 2 ] && {
echo "must two"
exit 1
}
echo oldgirl
$$ Get current shell The process number of
$? Gets the return value of the last instruction executed (0 For success , Not 0 For failure )
(1) The application case : When there is only one script and only one process running in the system
# pid.sh Script files
[[email protected] scripts]# cat pid.sh
#!/bin/sh
pidPath=/tmp/a.pid
if [ -f "$pidPath" ]
then
kill -USR2 `cat $pidPath`
rm -f $pidPath
fi
# script pid write to $pidPath
echo $$ >$pidPath
sleep 300
# Check the process
[[email protected] scripts]# ps -ef|grep pid.sh|grep -v grep
root 1758 1457 0 10:03 pts/0 00:00:00 sh pid.sh
4. Numerical calculation of variables
Common calculation commands :(())、let、expr、bc( decimal )、$[]
I. (())) usage
[[email protected] scripts]# ((a=1+2**3-4%3))
[[email protected] scripts]# echo $a
8
[[email protected] scripts]# b=$((1+2**3-4%3))
[[email protected] scripts]# echo $b
8
[[email protected] scripts]# echo $((3>2))
1
[[email protected] scripts]# echo $((3<2))
0
Example : One at a time ( Unmixed operation ), That is, pass two numbers through parameters , Pass a calculation symbol , Produce results .
[[email protected] scripts]# cat d.sh
echo $(($1$2$3))
[[email protected] scripts]# sh d.sh 3*2
6
II. let usage
[[email protected] scripts]# i=2
[[email protected] scripts]# let i=i+8
[[email protected] scripts]# echo $i
10
[[email protected] scripts]# i=2
[[email protected] scripts]# i=i+8
[[email protected] scripts]# echo $i
i+8
III. expr usage
[[email protected] scripts]# expr 2 + 2
4
[[email protected] scripts]# expr 2+2
2+2
[[email protected] scripts]# expr $[2*3]
6
[[email protected] scripts]# expr $[2/3]
0
IIII. read usage
# -t timeout Set the input waiting time , The default unit is seconds .
# -p prompt Set the prompt message
[[email protected] scripts]# read -t 5 -p "pls input:" a
pls input:1
[[email protected] scripts]# echo $a
1
The third chapter Branch and loop structure
1. if Conditional sentence
# Single branch
if [ Conditions ]
then
Instructions
fi
# Double branch
if Conditions
then
Instruction set
else
Instruction set
fi
# Multiple branches
if Conditions
then
Instructions
elif Conditions
then
Instructions
...
else
Instructions
fi
Special way of writing :if [-f “$file1”]; then echo 1;fi amount to : [-f “file1”] && echo 1
Example 1: Single branch if Compare the size of two integers in conditional sentences .
[[email protected] scripts]# cat if-single.sh
#!/bin/sh
if [ 10 -lt 12 ]
then
echo "yes,10 is less than 12"
fi
Example 2: Use read And how to realize the comparison of the above integers by script parameter transfer ?
#!/bin/sh
read -p "pls input two num:" a b
if [ $a -lt $b ];then
echo "yes,$a less than $b"
fi
if [ $a -eq $b ];then
echo "yes,$a equal $b"
fi
if [ $a -gt $b ];then
echo "yes,$a greater than $b"
fi
Chapter four Example demonstration
1. Use for The cycle is /oldboy Create in batch under directory 10 File , The names are in the following order :
oldboy-1.html,oldboy-2.html,…,oldboy-10.html
[[email protected] oldboy]# cat /home/scripts/01.sh
[ ! -d /oldboy ] && mkdir -p /oldboy
for i in `seq 10`
do
touch /oldboy/oldboy-${i}.html
done
2. use for The loop implementation will... In the above file name oldboy All changed linux, And the extension is changed to uppercase . requirement :for The circular body of a cycle cannot appear oldboy character string .
[[email protected] scripts]# cat 02.sh
#!/bin/sh
cd /oldboy
for f in `ls *.html`
do
mv $f `echo $f|sed 's#oldboy#linux#g'|sed 's#html#HTML#g'`
done
3. Batch creation 10 A system account oldboy01-oldboy10 And set the password ( Passwords cannot be the same ).
#!/bin/sh
for n in `seq -w 10`
do
useradd oldboy$n&&\
echo "root$n"|passwd --stdin oldboy$n
done
4. Array definition, addition, deletion, modification and query
[[email protected] scripts]# array=(1 2 3)
[[email protected] scripts]# echo ${#array[@]}
3
[[email protected] scripts]# echo ${#array[*]}
3
[[email protected] scripts]# echo ${array[0]}
1
边栏推荐
- Dart: view the dill compiled code file
- Develop plug-ins for idea
- shardingSphere分库分表<3>
- Solve msvcp120d DLL and msvcr120d DLL missing
- ArcGIS application (XXI) ArcMap method of deleting layer specified features
- Flutter Widget : Flow
- (构造笔记)MIT reading部分学习心得
- QT OpenGL texture map
- [combinatorics] permutation and combination (example of permutation and combination)
- Colleagues wrote a responsibility chain model, with countless bugs
猜你喜欢
Unicode encoding table download
ES6 standard
ES6新特性
Itext7 uses iexternalsignature container for signature and signature verification
Talk about the state management mechanism in Flink framework
Download address and installation tutorial of vs2015
Solution to the second weekly test of ACM intensive training of Hunan Institute of technology in 2022
Integer int compare size
Colleagues wrote a responsibility chain model, with countless bugs
OPenGL 基本知识(根据自己理解整理)
随机推荐
Dart: About zone
Qt OpenGL 旋转、平移、缩放
[combinatorics] permutation and combination (summary of permutation and combination content | selection problem | set permutation | set combination)
安装electron失败的解决办法
OpenGL draws colored triangles
DNS multi-point deployment IP anycast+bgp actual combat analysis
(construction notes) learning experience of MIT reading
DEJA_ Vu3d - cesium feature set 053 underground mode effect
If you can't learn, you have to learn. Jetpack compose writes an im app (II)
Wrong arrangement (lottery, email)
网上炒股开户安不安全?谁给回答一下
PHP export word method (one MHT)
Integer string int mutual conversion
2.9 overview of databinding knowledge points
(构造笔记)ADT与OOP
ES6新特性
OpenGL index cache object EBO and lineweight mode
PHP导出word方法(一mht)
PHP export word method (phpword)
Differences between MySQL Union and union all