In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the LINUX shell script programming method is what the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe you read this LINUX shell script programming method is what the article will have a harvest, let's take a look at it.
one。 Introduction to shell
When a command is executed not on the command line, but from a file, the file is called a Shell script. Shell scripts are plain text files that are executed line by line in behavior units.
It is equivalent to a command translator.
two。 The writing of shell script 2.1 the creation of script
Create a script file using a text editor (or touch)
Syntax: touch a.sh
2.2 execution of scripts
Add executable permissions to the script
Syntax: chmod + x a.sh
Execute script commands:
(1). / a.sh
(2) sh a.sh
(3) source a.sh / / does not require x permission
2.3 script writing
Edit script: vim a.sh
#! / bin/bash / / the system executes scripts with the bash interpreter
Cd / etc/
Pwd / / command statement
three。 Shell feature 3.1 Redirect
Redirect output: overwrites the execution results of the command to the target file
Syntax: df > a.txt / / overwrite disk information to a.txt file
Redirect append: uname-p > > a.txt / / append processor type to a.txt
Redirect input:
Vim pass.txt
123456
Passwd-stdin jerry
< pass.txt //标准输入 tail -2 /etc/shadow //查看用户密码信息后两行 3.2管道符号 将左侧的命令输出结果,作为右侧命令的处理对象 cat a.txt |grep "123" //筛选出含字符串"123"的行 grep "bash$" /etc/passwd | awk -F: '{ print $1,$7 }' //-F:后要求有空格 例:提取根分区/的磁盘使用情况 df -hT //查看磁盘使用情况-h显示更易读-T显示文件系统类型 df -hT | grep "/$" | awk '{print $6}' 四. shell变量 shell变量用来存放系统和用户需要使用的特定参数(值),而且这些参数可以根据用户的设定或系统环境的变化而相应变化。 4.1自定义变量4.1.1定义一个新的变量(输入) 格式:变量名=变量值 4.1.2查看变量的值(输出) 格式:echo $变量名 echo命令的选项: -n:取消自动换行 -e:使用转义字符,把字符串中某些字符当成特殊字符处理 \t:制表符 \n:换行符 \b:删除前一个字符 \f:换行但光标仍旧停留在原来的位置 \r:光标移至行首,但不换行 赋值时使用引号 双引号:允许通过$符号引用其他变量值 单引号:禁止引用其他变量值,$视为普通字符 反撇号:命令替换,提取命令执行后的输出结果 4.1.3从键盘输入内容为变量赋值(提示输入) 格式: read [-p "提示信息"] 变量名 4.2整数变量运算 Shell变量的数值运算多用于脚本程序的过程控制,只能进行整数运算,不支持小数 运算。整数的运算主要通过内部命令Expr进行。 格式:expr 变量1 运算符 变量2 [运算符 变量3]... //注意空格 常用运算符:加(+)、减(-)、乘(\*)、除(/)、取模(%) 例:设置X(值为35)、Y(值为16)两个变量,并进行加、减、乘、除、取模运算 X=35 Y=16 expr $X + $Y expr $X - $Y expr $X \* $Y //乘法符号在shell中有其它含义,运算时需要转意符号 expr $X / $Y expr $X % $Y 4.3环境变量 由系统提前创建,用来设置用户的工作环境 配置文件:/etc/profile 、~/.bash_profile env :查看当前工作环境下的环境变量。 这表示为 $n,n为1~9之间的数字 例:编写一个加法运算的小脚本a.sh,用来计算两个整数的和。需要计算的两个整数在执行脚本时以位置变量的形式提供。 #vim a.sh #!/bin/bash SUM=`expr $1 + $2` echo "$1 + $2 = $SUM" #chmod +x a.sh #./a.sh 12 24 //$1为12、$2为24 4.4预定义变量 是由Bash程序预先定义好的一类特殊变量,使用"$"符号和另一个符号组合表示。 $# :命令行中位置变量的个数 $* :所有位置变量的内容 $? :表示上一条命令执行后返回的状态,当返回状态值为0时表示执行正常,非0值表示执行异常或出错 $0 :当前执行的进程/程序名 例:编写一个备份小脚本 #vim mybak.sh #!/bin/bash TARFILE=beifen-`date +%s`.tgz tar zcf $TARFILE $* &>/ dev/null
Echo "executed $0 script,"
Echo "backups of $# objects in total"
Echo "details include: $*"
# chmod + x mybak.sh
#. / mybak.sh / boot/grub
#. / mybak.sh / etc/passwd / etc/shadow
five。 Test script Command 5.1 conditional Test
Test whether a specific expression is valid. When the condition is true, the return value of the test statement is 0, otherwise it is other values.
Format 1:test conditional expression
Format 2: [conditional expression] / / pay attention to the space. There is a space between the square brackets and the expression.
After performing the conditional test operation, through the predefined variable "$?" Gets the return status value.
5.2 File testing
According to the given path name, determine whether the corresponding file or directory, or whether the file is readable, writable, executable, and so on.
Usage: [operator file or directory]
-d: test whether it is a directory (Directory)
-e: test whether a directory or file exists (Exist)
-f: test whether it is a file (File)
-r: test whether the current user has the right to read (Read)
-w: test whether the current user has the right to write (Write)
-x: test whether executable permissions are set (Excute)
Example:
[- d / media/cdrom]
Echo $?
0 / / return 0 means the condition is valid, and return 1 means the condition is not valid
Use logic to display the results more intuitively with the & & and echo commands
[- d / media/cdrom] $$echo "yes"
Yes
5.3 Integer value comparison
Judge the relationship between the first and the second number according to the given two integer values
Usage: [integer 1 operator integer 2]
-eq: equal to (Equal)
-ne: not equal to (Not Equal)
-gt: greater than (Greater Than)
-lt: less than (Lesser Than)
-le: less than or equal to (Lesser or Equal)
-ge: greater than or equal to (Greater or Equal)
Example: judge the number of currently logged-in users, and output "Too many" if more than five users are logged in.
Unum= `who | wc-l` / / View the number of currently logged-in users
[$Unum-gt 5] & & echo "Too many."
5.4 string comparison
It is usually used to check whether the user input, system environment, etc., meet the conditions.
Usage 1: [string 1 = string 2] [string 1! = string 2]
Usage 2: [- z string] / / check whether it is empty
Generic: [string 1 operator string 2]
Example 1: judge the current system language, not "Not http://en.US" when http://en.US"
Echo $LANG
[$LANG! = "http://en.US"] & & echo" Not http://en.US"
Example 2: the user needs to enter yes or no to confirm the operation
Read-p "overwrite existing files (yes/no)?" ACK
[$ACK = "yes"] & & echo "overwrite"
Read-p "overwrite existing files (yes/no)?" ACK
[$ACK = "no"] $$echo "do not overwrite"
5.5 Logic Test
Judge the relationship between two or more conditions
Usage 1: [expression 1] operator [expression 2]
Usage 2: command 1 operator command 2
& &: logic and, "and" can be changed to "- a" when using the test command
| |: logic or, "or", which can be changed to "- o" when using test command |
!: logic No, "No"
Example: test whether the current system kernel version meets the requirements
Uname-r
Mnum=$ (uname-r | awk-F. '{print $1}')
Snum=$ (uname-r | awk-F. '{print $2}')
[$Mnum-eq 2] & & [$Snum-gt 4] & & echo "meets the requirements"
six。 If conditional statement
According to complexity: single-branch if statement, double-branch if statement, multi-branch if statement
6.1 single branch if statement
A corresponding piece of code is executed only if the condition is established.
Usage:
If conditional test
Then command sequence
Fi
Example: determine whether the mount point directory exists, and create a new directory if it does not exist
Vim chkmountdir.sh
#! / bin/bash
MOUNT_DIR= "/ media/cdrom/"
If [!-d $MOUNT_DIR]
Then
Mkdir-p $MOUNT_DIR
Fi
Chmod + x chkmountdir.sh / / permission for chkmountdir.sh to execute
. / chkmountdir.sh
6.2 two-branch if statement
Usage:
If conditional test operation
Then command sequence 1
Else Command sequence 2
Fi
Example: check whether the target host can be connected and display the corresponding information
Vim pinghost.sh
#! / bin/bash
Ping-c 3-I 0.2-w 3 $1 & > / dev/null / / do not read the messages when the command is executed
If [$?-eq 0] / / determines the return status of the previous command
Then
Echo "Host $1 is up."
Else
Echo "Host $1 is down."
Fi
Chmod + x pinghost.sh
. / pinghost.sh 192.168.4.11
6.3Multibranch if statement
Usage:
If conditional Test Action 1
Then command sequence 1
Elif conditional Test Action 2
Then Command sequence 2
Else
Command sequence 3
Fi
Example: judge the range of scores and divide them into excellent, qualified and unqualified third gears.
Vim gradediv.sh
#! / bin/bash
Read-p "Please enter your score (0-100):" GRADE
If [$GRADE-ge 85] & & [& GRADE-le 100]
Then
Echo "$GRADE score! excellent"
Elif [$GRADE-ge 70] & & [& GRADE-le 84]
Then
Echo "$GRADE score, qualified"
Else
Echo "$GRADE score? not qualified"
Fi
Chmod + x gradediv.sh
. / gradediv.sh
seven。 For loop statement
Read different variables to execute the same set of commands one by one
Usage:
For variable name in value list
Do
Command sequence
Done
Example 1: add users in batches according to the name list
Vim / root/users.txt / / used as a test list file
Jdy
Ttl
Tcc
Vim uaddfor.sh
#! / bin/bash
ULIST=$ (cat / root/users.txt)
For UNAME in $ULIST / / read the user name from the list file
Do
Useradd $UNAME
Echo "123456" | passwd-- stdin $UNAME & > / dev/null
/ / specify a password string through a pipe
Done
Chmod + x uaddfor.sh
. / uaddfor.sh
Tail-3 / etc/passwd
Example 2: check host status according to IP address list
Vim / root/ipadds.txt
192.168.4.11
192.168.4.100
192.168.4.120
Vim chkhosts.sh
#! / bin/bash
HLIST=$ (cat / root/ipadds.txt)
For IP in $HLIST
Do
Ping-c 3-I 0.2-W 3$ IP & > / dev/null
If [$?-eq 0] / / nested if statements to determine connectivity
Then
Echo "Host $IP is up."
Else
Echo "Host $IP is down."
Fi
Done
Chmod + x chkhosts.sh
. / chkhosts.sh
For loop statements are ideal for irregular list objects and the list source is fixed. However, when it is required to control the number of loops, operands are numbered in numerical order, and repeated operations are performed according to specific conditions, while loop statements are more suitable.
eight。 While loop statement
Repeatedly test a condition and execute it repeatedly as long as the condition is established
Usage:
While conditional test operation
Do
Command sequence
Done
Example: users who add regular numbers in batches
# vim uaddwhile.sh
#! / bin/bash
PREFIX= "stu"
I, 1
While [$I-le 20]
Do
Useradd ${[PREFIX} $I
Echo "123456" | passwd-- stdin ${PREFIX} $I & > / dev/null
Let iTunes + / / sequence number increments to avoid an endless loop
Done
Chmod + x uaddwhile.sh
. / uaddwhile.sh
Grep "stu" / etc/passwd | tail-3
For example: in the price guessing game, the script is required to generate a random number of prices (0-99) in advance as the actual price, judge whether the price guessed by the user is higher or lower than the actual price, and ask the user to guess again after giving the corresponding hint. Until the user guesses the actual price, output the number of times the user guesses and the actual price.
# vim pricegame.sh
#! / bin/bash
PRICE=$ (expr $RANDOM% 1000) / / enter price a random number
TIMES=0
Echo "the actual price range of goods is 0-999, guess what it is?"
While true / / Loop condition: true
Do
Read-p "Please enter the number of prices you guess:" INT
Let TIMES++
If [$INT-eq $PRICE]; then
Echo "Congratulations on your correct answer. The actual price is $PRICE."
Echo "you guessed a total of $TIMES times"
Exit 0
Elif [$INT-gt $PRICE]; then
Echo "too high!"
Else
Echo "too low!"
Fi
Done
Chmod + x pricegame.sh
. / pricegame.sh
nine。 Case branch statement
Execute different command sequences according to different values of variables
Usage:
Case variable value in
Mode 1)
Command sequence 1
Mode 2)
Command sequence 2
.
*)
Default command sequence
Esac
Example: check the type of characters entered by the user
Prompt the user to input a character from the keyboard, judge whether the character is a letter, number or other control character through the case statement, and give the corresponding prompt information.
# vim hitkey.sh
#! / bin/bash
Read-p "Please enter a character and press enter to confirm:" KEY
Case "$KEY" in
[amurz] | | [Amurz])
Echo "you typed in letters."
[0-9])
Echo "you entered a number."
*)
Echo "you entered spaces, function keys, or other control characters."
Esac
Chmod-x hitkey.sh
. / hitkey.sh
ten。 Brief introduction of sed and awk statement 10.1 Sed
Sed, which stands for stream editor, is an online editor that processes one line of content at a time. Sed is a non-interactive editor.
When processing, the currently processed line is stored in a temporary buffer, called "pattern space" (pattern space), and then the contents of the buffer are processed with the sed command, and when the processing is completed, the contents of the buffer are sent to the screen. Then process the next line, which is repeated until the end of the file. The contents of the file have not changed unless you use redirect to store the output.
10.2 Sed command usage
Format: sed+ [option] + 'command' + file name
Common options:
-n: cancel default input
-e: multiple editors
-I: directly modify the contents of the read file, rather than output by the screen
Common commands:
A\: add a line after the current line
I\: add a line before the current line
C\: replace lines with strings
D: delete Lin
P: print Lin
S: replace one string with another
W: writes the selected line to the file
10.3 Sed addressing
Before using the 'command', decide which lines to edit.
If no address is specified, sed processes all lines of the input file.
1. If the address is a number, it represents the line number; if it is a "$" symbol, it represents the last line.
two。 You can specify a range of addresses, separated by commas (,) when you need to specify a range.
10.4 Sed usage
1.p command
Format: sed-n 'line number p' file name
2.d command
Format: sed-n 'line number d' file name
3.s command
Format: sed-n 'line number sqqqa _ b _ 'filename
Replace all a characters in the specified line in the file with b characters, and g is the global variable
4.i command
Format: sed-I 'line number 3d' file name
Modify the contents of the file directly and do not print it on the screen
5.e command
Format: sed-e '3d'-e' 4p' file name
Delete the third line before printing the fourth line of characters
10.5 introduction to awk
Awk is a powerful text analysis tool, compared with the search of grep and the editor of sed, awk is particularly powerful in analyzing data and generating reports.
To put it simply, awk is to read the file line by line, slice each line with a space as the default separator, and then analyze the cut part.
10.6 awk usage
1. Format: awk 'pattern {action}'
Pattern often refers to relational expressions, such as:
Awk'/a/'file-- displays the lines in the file that contain a
Awk'$2 > 10 percent filemusic-displays rows with digits greater than 10 in the second column
two。 Separate extraction: awk-F "delimiter"'{print $1}'
For example:
Awk-F.' {print $1, print $2} 'means to output the first two fields of each line with a dot delimiter
10.7 awk instance
Determine the validity of the input ip:
Vim a.sh
#! / bin/bash
Read-p "Please enter ip:" A
B = `echo $A | awk-F. "{print $1}" `
If [$B-le 0] | | [$B-gt 255]
Then echo "Please enter the correct IP"
Else
Echo "ok"
Fi
Chmod + x a.sh
Sh a.sh
eleven。 Shell instance
Example 1: write a system service script
Vim myprog
#! / bin/bash
Case "$1" in
Start)
Echo-n "starting sleep service..."
If sleep 7200 &
Then
Echo "OK"
Fi
Stop)
Echo-n "stopping sleep service..."
Pkill "sleep" & > / dev/sull
Echo "OK"
Status)
If pgerp "sleep" & > / dev/sull
Then
Echo "sleep service has been started."
Else
Echo "sleep service has been stopped."
Fi
Restart)
$0 stop
$0 start
Esac
Chmod + x myprog
. / myprog start
Example 2: shell prints 99 multiplication tables
Use for Loop
For i in $(seq 1 9)
Do
For j in $(seq 1$ I)
Do
Echo-n "$j * $I" = $[I * j] "
Done
Echo
Done
/ / in the example, $[I * j] can be written as: $((I * j)), $[$jackers / I], $(($jacks / I)), `expr $I\ * $j`
/ / modify: add a line let "temp = I * j" under the second do, and then change $[I * j] to: $temp
While reverse multiplication table:
ITunes 9
Jroom1
While ((I > = 1)
Do
While (j
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.