In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
Basic script programming of bash and shell
Command execution with many bash features: separated by semicolons, no relationship between commands
] # cmd
Method 1:] # cmd1 `cmd2`: command reference to achieve multiple commands
Method 2:] # cmd1 | cmd2 | cmd3 |.: pipeline implements multiple commands
Method 3:] # cmd1;cmd2;cmd3;...: semicolon to achieve multiple commands
Logical combination: the operation is the running status of the command and the result is the exit code.
] # cmd1 & & cmd2 & &...
] # cmd1 | | cmd2 | |.
] #! cmd1
Exit code:
0: expressed as true, true, success, successful
1-255: represented as failure, false, error
Logical operation: the main operation is the running status of the command, that is, the exit code.
It can be thought that there is a judgment mechanism in it; the judgment depends on whether it is related to the operation or the operation also depends on the result of the first operation.
Operands: true (1), false (0)
COMMAND running status results:
0:TRUE, successful
1-255:FALSE, error
And: see false (0) is false (0); equivalent to multiplication
True & & true = true
True & & false = false
The first Operand is true, and the result depends on the second Operand
False & & true = false
False & & false = false
The first Operand is false, and the result can be determined to be false
For example:
] # ls / var & & cat / etc/fstab
] # lls / var & & cat / etc/fstab
Or: see true (1) for true (1); equivalent to addition
True | | true = true
True | | false = true
The first Operand is true, and the result can be determined to be ture
False | | true = true
False | | false = false
The first Operand is false, and the result depends on the second Operand
For example:
] # id hive | | useradd hive: if the user does not exist, add the user
] # id hive
Non: inverted
! True = false
! Fase = true
For example:
] #! Id hive & & useradd hive: if the user does not exist, add the user
Priority: non (high) / dev/null | | useradd user2
User1_id=$ (id-u user1)
User2_id=$ (id-u user2)
Id_sum=$ [$user1_id+$user2_id]
Echo "the id sum: $id_sum"
Enhanced variable assignment:
+ =,-=, * =, /,% =
Itself equals itself + numeric value, use the let command
For example:
] # declare-iitem1
] # iTunes $[$item1]
] # echo $I
Enhanced assignment is now available:
] # let iTunes 1
The variable is saved back to this variable after doing some arithmetic operation
Let i=$i+#
Let iTunes #
#: representative number
Self-increasing:
VAR=$ [$VAR+1]
Let VAR+=1
Let VAR++
Self-subtract:
VAR=$ [$VAR-1]
Let VAR-=1
Let VAR--
Exercise:
1. Script implementation to calculate the sum of the ID numbers of the 15th user and the 18th user in the / etc/passwd file
Decompose: do the calculation of 2 id numbers, id_sum=$ [$id1+$id2]
$(head-15 / etc/passwd | tail-1 | cut-d:-f3)
Baked $(head-18 / etc/passwd | tail-1 | cut-d:-f3)
Sum=$ [$axifolb]
Echo "the an is:$a"
Echo "the b is: $b"
Echo "teh sum is: $sum"
2. Calculate the sum of blank lines in / etc/rc.d/init.d/functions and / ect/inittab files
$(egrep "^ [[: space:]] * $" / etc/rc.d/init.d/functions | wc-l)
$(egrep "^ [[: space:]] * $" / etc/rc.d/init.d/network | wc-l)
Sum=$ [$axifolb]
Echo "an is: $a"
Echo "b is $b"
Echo "sum is: $sum"
Conditional testing for bash scripting:
To judge whether a requirement is met or not, it needs to be realized by the testing mechanism.
How to write test expressions to implement the required tests:
For example, to judge whether a file has blank lines or whether a user exists.
(1) execute the command and use the return value of the command status to judge
0: successful
1-255: failed
$?: stores the return value of the execution status of the previous command
For example:
Determine whether the user centos is logged in to the system:
Who | grep "^ centos\ >"
Echo $?: displays the return value of the previous command status
Get the return value of command status. 0: login, 1-255: not logged in
(2) Test expression
Test EXPRESSION
[EXPRESSION]
`EXPRESSION'
When comparing characters, use double parentheses
Note: there must be white space characters at both ends of the EXPRESSION, otherwise the syntax is wrong.
Test types for bash scripting:
Numerical test
String test
File testing
Numerical testing: comparison between numerical values
-eq: whether it is equal to; for example: [$num1-eq $num2], test 2-eq 3 or [2-eq 3]
-ne: is it not equal to
-gt: whether it is greater than
-ge: whether it is greater than or equal to
-lt: whether it is less than
-le: whether less than or equal to
For example:
] # test 2-gt 3
] # [$A-eq $B]
Exercise:
Is the id of centos users larger than the ID of ubuntu users?
Await $(id-u centos)
Baked $(id-u ubunto)
[$a-gt $b] & & echo "centos is bigger" | | echo "ubuntu is bigger"
String test comparison
=: whether it is equal to or equal to true
! =: whether it is different or not does not mean it is true
>: whether it is greater than, greater than is true
/ dev/null | | useradd mageedu & & exit 5
Or: id mageedu & > / dev/null & & exit 5 | | useradd mageedu
Bash script programming passes parameters to the script
Position parameter variable
Command line: * .sh argu parameter 1 argu parameter 2 argu parameter 3.
Quote in the script: $1 $2 $3.
Myscript.sh agru1 argu2...
Citation method:
$1: save argu parameter 1
$2: save argu parameter 2
...
${10}, ${11}.
Rotation:
Shift [n]: position parameter rotation. N is the number and defaults to 1. It is expressed as the first few parameters of a rotation.
$1 for 2. It is called position parameter variables, and the values of these parameter variables are changed by passing parameter changes each time the script is run.
For example:
My_shell.sh ubuntu centos linux
Citation method:
Use $1 in the script "2" 3
Useradd $1
Useradd $2
Useradd $3
Explanation: $1 ubuntu, 2 century, 3 Linux.
Shift #: delete the specified parameter; add the following parameters to the front
Exercise:
Script implementation, passing two text paths to the script through the command to calculate the sum of its blank lines (^ $)
$(egrep "^ $" $1 | wc-l)
Baked $(egrep "^ $" $2 | wc-l)
Sum=$ [$axifolb]
Echo "an is: $a"
Echo "b is $b"
Echo "sum is: $sum"
Shift #: automatically kicks out command parameters
Special variables:
$0: save the script file path itself
$#: the number of script parameters saved
$*: save all parameters; display each parameter as an independent parameter
$@: save all parameters; put each parameter together and display it as a string parameter
$0: indicates the path of the script file given by the command line
For example: command line] # bash / tmp/parameter_blanksum.sh
Script content: echo $0
The display result is: / tmp/parameter_blanksum.sh
If the command line is: bash parameter_blanksum.sh
The content of the script remains unchanged, and the display result is: parameter_blanksum.sh
$#: indicates the number of script parameters
For example:
] # bash parameter_blanksum.sh / etc/init.d/functions / etc/init.d/network
Script content: echo $#
The display result is: 2
$*: indicates that the parameter is multiple strings
$@: indicates that the parameter is a string
For example: command line] # bash parameter_blanksum.sh / etc/init.d/functions / etc/init.d/network
Script content: echo $*
Echo $@
The display result is: / etc/init.d/functions / etc/init.d/network
/ etc/init.d/functions / etc/init.d/network
But $* is represented as two separate paths, while $@ is represented as an entire behavior and a string.
Exercise:
1. Determine whether / etc/passwd is a file. If it is a file, output / etc/passwd is files. The path is passed through commands. When the number of commands passed in is greater than 1, an error is reported.
[$#-gt 1] & & echo "something wrong" & & exit
[- f $1] & & echo "/ etc/passwd is files"
2. Write a script in the root directory and add 3 users at once. You can add users by passing parameters. If the passed parameters do not match 3, an error will be reported.
When the three users are added, the script needs to be reinforced (lock mechanism, which can no longer be executed), and the permissions of the script need to be changed to owner readable, writable and executable.
! [$#-eq 3] & & echo "please give me three username" & & exit 1
Useradd $1 & & axi1
Useradd $2 & & baked 1
Useradd $3 & & Clear1
Sum=$ [$a+$b+$c]
[$sum-eq 3] & & echo "$1 $2 $3" | | exit 2
Chmod 7000.00
Echo $1 is added
Echo $2 is added
Echo $3 is added
Echo "this scripts mode is 700"
Or:
[$#-gt 3] | | [$#-lt 3] & & echo "something wrong,give three user" & & exit 1
Id $1 & > / dev/null & & echo "$1 exist" | | useradd $1
Id $2 & > / dev/null & & echo "$2 exist" | | useradd $2
Id $3 & > / dev/null & & echo "$3 exist" | | useradd $3
Echo "three users $1, 2, 3, are added success"
Chmod 7000.00
Echo "this script mode is 700"
The code execution order of the procedural programming language:
Sequential execution: run one by one
Select execute:
There is a branch of the code: it will not be executed until the condition is met.
Two or more branches: only one of the branches that meets the criteria will be executed
Loop execution:
A code snippet (loop body) to perform 0, 1 or more back and forth (loop)
Sequential execution
Condition selection:
(1) &, | |
(2) if statement (single branch, double branch, multi-branch)
(3) case statement
Loop execution: for,while,until
If statement selection Branch of bash script programming
Condition judgment:
Shell execution is executed sequentially
Select Branch
Single branch if statement
If test condition; then (if the condition is true, execute the following statement)
Code branch
Fi
Or
If test condition
Then
Code branch
Fi
Double-branched if statement
If test condition; then
Branch executed when the condition is true
Else
Branch executed when the condition is false
Fi
Multi-branch if statement
If test condition; then
Branch executed when the condition is true
Elif test condition; then
Elif test condition; then
Elif test condition; then
Else
A branch that is executed when the condition is false
Fi
For example:
Pass a user name to the script through the parameter, and create the user if the user does not exist
If! Grep "^ $1\ >" / etc/passwd & > / dev/null;then
Useradd $1
Echo $1 | passwd-- stdin $1 & > / dev/null
Echo "add a user $1 finished"
Else
Echo "$1 is exist"
Fi
Example: pass a user name to the script through the parameter, and add it when the user does not exist. (to judge the expression: one is a command, the other is that the expression is placed in square brackets or represented by test to determine whether the user exists with id or grep)
~] # vim useradd.sh
If! Grep "^ $1\ >" / etc/passwd & > / dev/null;then
Useradd $1
Echo $1 | passwd-- stdin $1 & > / dev/null
Echo "add user $1 finished"
Fi
~] #. / useradd.sh hbase
The execution result is: add user hbase finished
A judgment if statement is added to determine whether the parameter exists or not:
~] # vim useradd.sh
If [$#-lt 1]; then
Echo "at least one username"
Exit 2
Fi
If! Grep "^ $1\ >" / etc/passwd & > / dev/null;then
Useradd $1
Echo $1 | passwd-- stdin $1 & > / dev/null
Echo "add user $1 finished"
Fi
~] #. / useradd.sh hbase
Change to a two-branch judgment if statement:
~] # vim useradd.sh
If [$#-lt 1]; then
Echo "at least one username"
Exit 2
Fi
If grep "^ $1\ >" / etc/passwd & > / dev/null;then
Echo "user $1 exists"
Else
Useradd $1
Echo $1 | passwd-- stdin $1 & > / dev/null
Echo "add user $1 finished"
Fi
~] #. / useradd.sh hbase
Exercise:
1. Through the command parameters, two numbers are given, and the larger number is output.
If [$1-gt $2]; then
Echo $1 is bigger
Else
Echo $2 is bigger
Fi
Or:
If [! $#-eq 2]; then
Echo "give two number"
Exit 2
Fi
If [$1-gt $2]; then
Echo "the bigg is $1"
Elif [$1-lt $2]; then
Echo "the bigg is $2"
Else
Echo "$1 million 2"
Fi
2. Through the command parameter, two text file names are given, and if a file does not exist, the script ends. If there is a number of lines returned to each file, and echo the file name with more lines.
[$#-ne 2] & & echo "give two file" & & exit 1
If! [- e $1]; then
Echo "$1 is not find"
Exit 2
Elif! [- e $2]; then
Echo "$2 is not find"
Exit 3
Fi
F1 dollars (cat $1 | wc-l)
F2salary $(cat $2 | wc-l)
Echo "$1 line is $F1"
Echo "$2 line is $f2"
If [$F1-gt $f2]; then
Ehco "$F1 is more"
Elif [$F1-eq $f2]; then
Echo "F1 and f2 the same"
Else
Echo "$f2 is more"
Fi
Or:
If! [$#-eq 2]; then
Echo "give 2 files"
Exit 20
Elif! [- e $1]; then
Echo "$1 is not exist"
Elif! [- e $2]; then
Echo "$2 is not exist"
Exit 30
Else
F1 dollars (cat $1 | wc-l)
F2salary $(cat $2 | wc-l)
Echo "f1=$f1"
Echo "f2=$f2"
Fi
If [$F1-gt $f2]; then
Echo "file1 line is more: $F1"
Echo "$(basename $1) line is more"
Elif [$F1-lt $f2]; then
Echo "file2 line is more: $f2"
Echo "$(basename $2) line is more"
Else
Echo "f1-$f1 and f2-$f2 is same"
Fi
3. Give a user name through the command line parameter to determine whether the ID number is even or odd.
Multi-branch if statement
Select execute:
(1) &, | |
(2) if statement
(3) case statement
If statement: three formats
Single branch if statement
If CONDITION;then
If-ture- branch
Fi
Double-branched if statement
If CONDITION;then
If-true- branch
Else
If-false- branch
Fi
Multi-branch if statement
If CONDITION1;then
Condition 1 is a true branch.
Elif CONDITION2;then
Condition 2 is a true branch.
Elif CONDITION3;then
Condition 3 is a true branch.
...
Elif CONDITIONn;then
Conditional nweizhen bifurcation
Else
Branch when all conditions are not met
Fi
Note: even if multiple conditions may be met at the same time, the branch will only execute one of them. After the conditional branch whose first test is true is executed, it will exit.
Example: pass the file path to the script to determine the type of the file through the script parameters
If [$#-lt 1]; then
Echo "at lease one path"
Exit 1
Fi
If! [- e $1]; then
Echo "no such file"
Eixt 2
Fi
If [- f $1]; then
Echo "common file"
Elif [- d $1]; then
Echo "directory file"
Elif [- L $1]; then
Echo "symbolic link file"
Elif [- b $1]; then
Echo "block special file"
Elif [- p $1]; then
Echo "pipe file"
Elif [- S $1]; then
Echo "socket file"
Elif [- c $1]; then
Echo "character special file"
Case statements are actually simplified versions of multi-branch if statements, but not all if statements can be converted into case statements
Note: if statements can be nested to use
Exercise:
1. Write scripts to achieve the following functions:
(1) pass a parameter to the script, which is the user name
(2) judge the type of user according to its id
0: administrator
1-999: system user
1000 hours: login user
(3) if it does not exist, you can add this user.
[$#-lt 1] & & echo "at least one username" & & exit 1
! Id $1 & > / dev/null & & echo "no such user" & & exit 2
Userid=$ (id-u $1)
If [$userid-eq 0]; then
Echo "root"
Elif [$userid-ge 1000]; then
Echo "login user"
Else
Echo "system user"
Fi
2. Write scripts to achieve the following functions:
(1) list the following menus for users
Disk) show disks info (fdisk-l / dev/sda)
Mem) show memory info (free-m)
Cpu) show cpuinfo (using cat / proc/cpuinfo or lscpu)
*) quit
(2) prompt the user to give his or her choice, and then display the corresponding system information corresponding to his or her choice
Cat / dev/null;then
Echo "$username exists"
Esle
Useradd $username & & echo "add user $username finished"
Fi
Done
For example: create 10 files F1-10 under the tmp directory
For filename in {1... 10}; do
Touch / tmp/f$filename
Done
Note: when, we should consider the judgment condition; as in the above example, we should first judge whether the file exists.
For example: find the sum of all positive integers within 100
Declare-I sum=0
For i in {1... 100}; do
Sum=$ [$sum+$i]
Done
Echo $sum
For example: calculate the odd number and the sum of 100
Declare-I sum=0
For i in $(seq 1 2 100); do
Sum=$ [$sum+$i]
Done
Echo $sum
For example: calculate the even number and sum within 100
Declare-I sum=0
For i in $(seq 2 2 100); do
Sum=$ [$sum+$i]
Done
Echo $sum
Example: determine the type of each file in the / var/log directory
File / var/log/* can be judged, but it is required to be implemented in a loop.
For filename in / var/log/*;do
If [- f $filename]; then
Echo "this is common file"
Elif [- d $filename]; then
Echo "this is directory file"
Elif [- L $filename]; then
Echo "this is softlink"
Elif [- b $filename]; then
Echo "this is block file"
Elif [- c $filename]; then
Echo "this is character file"
Elif [- S $filename]; then
Echo "this is socket file"
Elif [- p $filename]; then
Echo "thisi is pipe file"
Else
Echo "unknow file type"
Fi
Done
Exercise:
1. Find the sum of even numbers and odd numbers within 100 respectively
Calculate the odd number and sum within 100
Declare-I sum=0
For i in $(seq 1 2 100); do
Sum=$ [$sum+$i]
Done
Echo $sum
Calculate the sum of even numbers within 100
Declare-I sum=0
For i in $(seq 2 2 100); do
Sum=$ [$sum+$i]
Done
Echo $sum
2. Calculate the sum of the id of all users on the current system
Declare-I sum=0
For i in $(cut-d:-f3 / etc/passwd); do
Echo "\ $sum=$sum,\ $iSuppli"
Sum=$ [$sum+$i]
Done
Echo $sum
3. Pass a directory to the script through the script parameters, and then calculate the sum of the lines of all text files in this directory; and indicate the total number of such files
! [$#-eq 1] & & exit 1
! [- d $1] & & echo "please give a comment file" & & exit 2
Declare-I filesum=0
Declare-I sum=0
Declare-I Arom0
For i in $(ls $1); do
If [- f $I]; then
Cut $(wc-l $I | cut-d ""-F1)
Aphrodite 1
Sum=$ [$sum+$a]
Echo "file line sum=$a,files sum $A Magi all file line sum is $sum"
Else
Echo "this file not text type"
Fi
Done
For circular format:
For VARAIBLE in LIST;do
Cyclic body
Done
There are many ways to generate a LIST list: any command that can return a list, such as {#.. #} or glob (/ tpm/test/*), can be given directly.
Special uses of for loops:
For ((control variable initialization; conditional judgment expression; modified statement of control variable); do
Cyclic body
Done
Note: conditional judgment can be used directly.
Control variable initialization: executed only once when the loop code starts to run
Control variable correction statement: the control variable correction operation will be carried out at the end of each cycle, and then the condition judgment will be made.
Example: find the sum of integral positive numbers within 100
Declare-I sum=0
For ((item1witi > / tmp/users.log
Or rewrite it as:
Until who | grep "^ aaa\ >" & > / dev/null;do
Sleep 3
Done
Echo "$(date +" F% T ") aaa longed on" > > / tmp/user.log
Special use of the while loop (traversing the lines of the file):
While read VARIABLE;do
Cyclic body
Done
< /PATH/FROM/SOMEFILE 依次读取/PATH/FROM/SOMEFILE文件中的每一行,且将其值赋值给VARIABLE变量; 示例:找出ID号为偶数的用户,显示器用户名、ID及默认shell; while read line;do userid=$(echo $line |cut -d: -f3) username=$(echo $line |cut -d: -f1) usershell=$(echo $line |cut -d: -f7) if [ $[$userid%2] -eq 0 ];then echo "$username,$userid,$usershell" fi done < /etc/passwd bash脚本编程之用户交互 脚本参数 用户交互:通过键盘输入数据 read [OPTION] ... [name ...] -p 'PROMPT':输出提示符,设置提示信息;; -t TIMEOUT:设定超时退出时间; name:是在脚本里设定的变量; bash -n /path/to/some_script 检测脚本中的语法错误 bash -x /path/to/some_script 调试执行 例如:脚本实现,使用read添加用户,密码同用户名; read -p "plase give a username and passwd: " a b useradd $a echo $a echo $b echo "$b "| passwd $a --stdin &>/ dev/null
For example: script interaction, enter a specified user name, create a user and set a password
Read-p "Enter a username:" name
[- z "$name"] & & ehco "a username is needed" & & exit 2
Read-p "enter a passwd for $name, [passwd]:" passwd
[- z "$passwd"] & & passwd= "passwd"
If id $name & > / dev/null;then
Echo "$name exists"
Else
Useradd $name
Echo "$passwd" | passwd-- stdin $name & > / dev/null
Echo "add user $name finished"
Fi
Exercise:
1. Judge who is big and who is small when given two values.
A method of giving a numerical value; command parameters, command interaction
Read-p "give two number:" a b
! [$#-eq 2] & & echo "give two number" & & exit 1
If [$a-gt $b]; then
Echo "$an is bigger"
Else
Echo "$b is bigger"
Fi
2. Prompt the user to enter a string. If the input is quit, exit, otherwise the string content will be displayed.
Read-p "give a string:" a
If! [$a = = quit]; then
Echo "show string is $a"
Else
Exit 1
Fi
Background: new employees of the company should open system accounts and count out the information of new employees (through interaction)
Let the user specify a user name and password. If the user name exists before, delete it first, and then add the system account for the user.
After completion, you need to count the employee's mobile phone number, email,qq, age, and store them in the user's home directory after collection.
When the above is done, ask the user if he or she needs to create a separate working directory for the user as / data/username. The default is to do so. If not, enter n or N
Read-p "input a password for useradd:" password
Echo $password | passwd-- stdin $username & > / dev/null
Echo "user's password is add finished"
Read-p "input personal infomation:tel):" tel
Echo "$username tel:$tel" > > / home/$username/userinfo.txt
Read-p "input personal infomation:email):" email
Echo "$username email:$email" > > / home/$username/userinfo.txt
Read-p "input personal infomation:qq):" qq
Echo "$username qq:$qq" > > / home/$username/userinfo.txt
Read-p "input personal infomation:age):" age
Echo "$username age:$age" > > / home/$username/userinfo.txt
Read-p "you if create personal work DIR (ymp nrecom N) default: y:" dir
If ["$dir" = = "y"]; then
Mkdir-p / data/$username
Elif ["$dir" = = "n"-o "$dir" = = "N"]; then
Echo "you choice nocreate personal work DIR,bye"
Exit 2
Fi
Conditional selection of case statements for bash script programming
Case statement:
Multi-branch in statements in if:
If CONDITION1;then
Branch 1 (statement executed when CONDITION1 is true)
Elif CONDITION2;then
Branch 2 (statement executed when CONDITION2 is true)
...
Else CONDITION;then
Branch n
Fi
Example: display a menu to the user
Disk) show disk info
Mem) show memory info
Cpu) show cpu info
*) QUIT
Requirements: (1) prompt users to give their own choices
(2) the correct selection gives the corresponding information, otherwise, it is prompted to re-select the correct option.
Cat / dev/null;then
Grep "^ $username\ >" / etc/passwd | cut-d:-f3mem7
Else
Echo "no such user"
Fi
}
Username=$1
Userinfo
Username=$2
Userinfo
Example: rewrite script service framework (service scripts cannot end in .sh)
# chkconfig:-50 50
# description: test service script
#
Prog=$ (basename $0)
Lockfile=/var/lock/subsys/$prog
Start () {
If [- f $lockfile]; then
Echo "$prog is running yet"
Else
Touch $lockfile
Lockfile=/var/lock/subsys/$prog
Start () {
If [- f $lockfile]; then
Echo "$prog is running yet"
Else
Touch $lockfile
[$?-eq 0] & & echo "start $prog finished"
Fi
}
Stop () {
If [$lockfile]; then
Rm-f $lockfile
[$?-eq 0] & & echo "stop $prog finished"
Else
Echo "$prog is not running"
Fi
}
Restart () {
If [- f $lockfile]; then
Rm-f $lcokfile
Touch $lockfile
Echo "restart $prog finished"
Else
Touch-f $lockfile
Echo "start $prog finished"
Fi
}
Status () {
If [- e $lockfile]; then
Echo "$prog is running"
Else
Echo "$prog is stopped"
Fi
}
Usage () {
Echo "Usage: $prog {start | stop | restart | status}"
Exit 1
}
Case $1 in
Start)
Start
Stop)
Stop
Restart)
Stop
Start
Status)
Suatus
*)
Usage
Exit 1
Esac
The return value of the function:
The value returned from the execution result of the function:
(1) use the echo or printf command for output
(2) the execution result of the command called in the function body
Exit status code of the function:
(1) default depends on the exit status code of the last command executed in the function body
(2) Custom: use return #
There are two kinds of return values for commands, one is the return value for the execution result, and the other is the exit status code; when the command replacement is implemented in the script, the result of command execution is called at the place of command replacement, and so is the function. Function substitution is the place where the function is called, that is, the result of function code execution; printf command: no line wrapping is allowed, but the output can be defined as formatted output. It will be introduced in the awk command
The function can accept parameters:
Pass parameters to the function:
In the function body, you can use $1, $2,. Reference the parameters passed to the function; you can also use $* or $@ to refer to all parameters in the function, and $# to refer to the number of parameters passed
When calling a function, the given argument list is separated by a space character after the function name, for example, testfunction arg1 agr2 agr3...
Example: add 10 users, use the function implementation, and pass the user name as an argument to the function
] # bash-x exercise.sh aaa
Addusers () {
If id $1 & > / dev/null;then
Return 5
Else
Useradd $1
Retval=$?
Return $retval
Fi
}
For i in {1... 10}; do
Addusers ${1} ${I}
Retval=$?
If [$retval-eq 0]; then
Echo "add user ${1} ${I} finished"
Elif [$retval-eq 5]; then
Echo "user ${1} ${I} exist"
Else
Echo "unkown error"
Fi
Done
Exercise:
1. The script function implements the ping host to test the host's online status.
Main program: to test the online status of hosts in the range of 172.16.1.1-172.16.67.1
Implemented using for,while and until loops, respectively
Common way:
Declare-I uphosts=0
Declare-I downhosts=0
For i in {1... 67}; do
If ping-W 1-c 1 172.16.$i.1 & > / dev/null;then
Echo "172.16.$i.i is up"
Let uphosts+=1
Else
Echo "172.16.$i.1 is down"
Let downhosts+=1
Fi
Done
Echo "Up hosts: $uphosts,Down hosts: $downhosts"
Revision 2: function + while loop:
Declare-I uphosts=0
Declare-I downhosts=0
Declare-iionization 1
Hostping () {
If ping-W 1-c 1 $1 & > / dev/null;then
Echo "$i is up"
Let uphosts+=1
Else
Echo "$1 is down"
Let downhosts+=1
Fi
}
While [$I-le 67]; do
Hostping 172.16.$i.1
Let iTunes +
Done
Echo "Up hosts: $uphosts,Down hosts: $downhosts"
Revision 3: use return to count the number of hosts in ping in the main program
Declare-I uphosts=0
Declare-I downhosts=0
Declare-iionization 1
Hostping () {
If ping-W 1-c 1 $1 & > / dev/null;then
Echo "$i is up"
Return 0
Else
Echo "$1 is down"
Return 1
Fi
}
While [$I-le 67]; do
Hostping 172.16.$i.1
[$?-eq 0] & & let uphosts++ | | let downhosts++
Let iTunes +
Done
Echo "Up hosts: $uphosts,Down hosts: $downhosts"
2. Realize script function and print nn multiplication table.
Variable scope:
Local variable: the scope is the life cycle of the function; it is automatically destroyed at the end of the function
Method for defining local variables: local VARIABLE=VALE
Local variable: scope is the life cycle of the shell process that runs the script; therefore, its scope is the current shell script program file
For example:
Name=tom
Setname () {
Name=jerry
Echo "Function: $name"
}
Setnaem
Echo "Shell: $name"
In this case, the name of the function and the name of shell are both jerry, and the variable name is a local variable, which can be called in the function.
The display results are as follows:
Function:jerry
Shell: jerry
If it is changed to: local name=jerry in the above statement
The display results are as follows:
Function:jerry
Shell: tom
Function recursion for bash scripting:
Function calls itself directly or indirectly
Function recursion is used when doing factorial or Fibonacci series.
For example: 10! = 10: 9! = 10'9'8! = 10'9'8'7! ... = 10'9'8'7'6'5'4'3'2'1!
The factorial transfer parameter of the function is n
N * (nmur1)! = n* (nmel1) * (nmur2)! =.
For example: Fibonacci series
Each value is the sum of the first two numbers; a function is used to find out what the number of order n is.
1 1 2 3 5 8 13 21...
For example, the passing parameter is a number to realize the factorial of the number.
Fact () {
If [$1-eq 0-o $1-eq 1]; then
Echo 1
Else
Echo $[$1mm $(fact $[$1-1])]
Fi
}
Fact $1
For example: pass a parameter to a number to implement the Fibonacci sequence
Fab () {
If [$1-eq 1]; then
Echo-n "1"
Elif [$1-eq 2]; then
Echo-n "1"
Else
Echo-n "$[(fab $[$1-1]) + $(fab $[$1-2])]"
Fi
}
For i in $(seq 1 $1); do
Fab $I
Done
Ech
An array of bash script programming
Functions, case statements
Case statement syntax format:
Case $VARIABLE in
PAT1)
Branch 1
PAT2)
Branch 2
...
*)
Branch n
Esac
PATTERN: is a Glob wildcard
Function: can complete structured programming and realize code reuse
Function function_name {
Function body
}
Function_name () {
Function body
}
After the function is defined, the called function can be executed.
Function call: you can call a given function name, or you can pass parameters to the function, using the position parameter $1.
Local variable: local VARIABLE
When the life cycle is to call a function, the body of the function
Array:
Program = instruction + data
Instructions in bash scripts: syntax keywords in the whole programming, plus commands on various systems, plus defined functions
Data: exists in variables, files, or data organization structures
Variables: memory space that stores a single element
Array: contiguous memory space for storing multiple elements
Array name: the entire array has only one name; the number stored in the first memory space of the array is the location where the array name points.
Array index: the number starts at 0; the data method of referencing the array species:
Array name [index]
${ARRAY_ name [index]}
Note: bash-4 and later versions support custom indexing format, not just 0meme 1pm 2pm. Digital format
A generic group in a custom index format, called an associative array
Declare an array:
Declare-a NAME: declare an indexed array
Declare-A NAME: declare an associative array
View the statement help:
] # help declare
The data in the array is a continuous memory space that exists in memory, storing multiple consecutive data separately, each data is an independent managed unit, but there is no independent name, it should be indexed by the array name, and the array name plus a subscript can be understood as the identifier of the data in the array.
How the elements in the array are assigned:
(1) assign only one element at a time:
ARRAY_ name [index] = value
For example:
] # animals [0] = pig
] # animals [1] = cat
] # echo $animals
] # echo ${animals [1]}
(2) assign all elements at once:
ARRAY_NAME= ("VAL1", "VAL2", "VAL3"...)
Will automatically assign a value of 0, 1, 2, 3, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
For example:
] # weekdays= ("Monday"Tuseday"Wednesday")
] # echo ${weekdays [2]}
(3) only specific elements are assigned
ARRAY_NAME= ([0] = "VAL1" [3] = "VAL4"...)
An array in a sparse format
Note: bash supports arrays in sparse format
For example:
] # sword= ([0] = "Yitian" [3] = "Tulong")
] # echo ${sword [1]}: displayed as empty
] # echo ${sword [3]}: displayed as Tulong
(4) read-an ARRAY_NAME
For example:
] # read-a Linux
Sed awk find grep
] # echo ${Linux [1]}: displayed as awk
Associative array:
] # declare-A world: declare an associative array
] # world [us] "America"
] # echo "${world [us]}": displayed as America
] # world [uk] "unite kingdom"
] # echo "${world [uk]}": displayed as unite kingdom
Reference elements in the array: ${ARRAY_ name [index]}
Note: when referencing, only the array name is given, which indicates that the element with subscript 0 is referenced
${ARRAY_NAME [*]}: references all elements in the array
${ARRAY_NAME [@]}: ditto
Length of the array (number of elements in the array):
${# ARRAY_NAME [*]}
${# ARRAY_NAME [@]}
For example:
] # echo "${# Linux [*]}: displays the number of array elements 4
] # echo "${# animals [@]}: displays the number of array elements 2
] # echo "${# animals}: displays 3 characters for the first element of the array
] # echo "${animals [*]}: displays all elements in the array; generates a list
Example: generate 10 random numbers and find out the maximum and minimum values
Declare-a rand
Declare-I max=0
For i in {0.. 9}; do
Rand [$I] = $RANDOM
Echo ${rand [$I]}
[${rand [$I]}-gt $max] & & max=$ {rand [$I]}
Done
Echo "Max: $max"
Exercise:
1. Generate 10 random numbers, from small to sorted
2. Define an array whose elements are all files ending in .log in the / var/log directory; count the sum of lines in files whose subscript is even
Declare-a files
Files= (/ var/log/*.log)
Declare-I lines=0
For i in $(seq 0 $[${# files [*]}-1]); do
If [$[$I% 2]-eq 0]; then
Let lines+=$ (wc-l ${files [$I]} | cut-d'- F1)
Fi
Done
Echo "lines: $lines"
Reference all elements in the array:
${ARRAY_NAME [*]}
${ARRAY_NAME [@]}
You can also return only a limited number of elements
Array element slicing: ${ARRAY_NAME [@]: offset:number}
Offset: element offset
Number: take the number of elements; when number is omitted, all elements after the offset are taken
For example:
] # files= (/ etc/ [Pp] *)
] # echo ${files [*]}
Display the results:
/ etc/pam.d / etc/passwd / etc/passwd- / etc/pinforc / etc/pkcs11 / etc/pki / etc/plymouth / etc/pm / etc/polkit-1 / etc/popt.d / etc/postfix / etc/ppp / etc/prelink.conf.d / etc/printcap / etc/profile / etc/profile.d / etc/protocols / etc/pulse
] # echo ${files [@]: 2:3}: skips 2 from the above array and takes 3
Display the results:
/ etc/passwd- / etc/pinforc / etc/pkcs11
] # echo ${files [@]: 5}
Display the results:
/ etc/pki / etc/plymouth / etc/pm / etc/polkit-1 / etc/popt.d / etc/postfix / etc/ppp / etc/prelink.conf.d / etc/printcap / etc/profile / etc/profile.d / etc/protocols / etc/pulse
Append elements to an array in a non-sparse format:
ARRAY_NAME [${# ARRAY_NAME [*]}] =
${# ARRAY_NAME [*]}]: indicates the number of elements in the fetched array
Delete an element from the array:
Unset ARRAY [INDEX]
Associative array:
Declare-An ARRAY_NAME
ARRAY_NAME= ([index_name1] = "value1" [index_name2] = "value2"...)
Bash's built-in string processing tool for bash scripting:
String slicing: (string based on location)
${var:offset:number}: take a substring of a string
${var:-length}: take the rightmost characters of the string
Note: there must be a space after the colon
For example:
] # name=jerry
] # echo ${name:2}
Display result: rry
] # echo ${name:2:2}
Display result: rr
] # echo ${name:-4}
Display result: erry
Take the string based on the pattern:
${var#*word}:
Where word is a read-only delimiter; function: from left to right, find the first occurrence of the word delimiter in the string stored by the var variable, and delete all characters between the beginning of the string and the delimiter
${var##*word}: (can be used to get the path base name and port number)
Where word is a read-only delimiter; function: from left to right, find the last word delimiter in the string stored by the var variable, and delete all characters between the beginning of the string and the delimiter
For example:
] # mypath= "/ etc/init.d/functions"
] # echo ${mypath#*/}: display content: etc/init.d/functions
] # echo ${mypath##*/}: display content: functions; (take the base name of the path)
${var%word*}: (can be used to get a path name)
Where word is a read-only delimiter; function: from right to left, find the word delimiter that appears for the first time in the string stored by the var variable, and delete all characters from the delimiter to the end of the string
${var%word*}:
Where word is a read-only delimiter; function: from right to left, find the last word delimiter in the string stored by the var variable, and delete all characters from the delimiter to the end of the string
For example:
] # echo ${mypath%/*}: display content: / etc/init.d; (that is, the path name)
] # echo ${mypath%%/*}: display content: empty
] # mypath= "etc/init.d/functions"
] # echo ${mypath%%/*}: display content: etc
] # url= "http://www.magedu.com:80"
] # echo ${url##*:}: display content: 80; (take port number)
] # echo ${url%%:*}: display content: http
Find and replace:
${var/PATTERN/SUBSTI}:
Find the string represented by var that is matched by PATTERN for the first time and replace it with the string represented by SUBSTI
${var//PATTERN/SUBSTI}:
Find all the strings matched by PATTERN in the string represented by var and replace them all with the string represented by SUBSTI
Anchor at the beginning / end of the line:
${var/#PATTERN/SUBSTI}:
Find the string represented by var to which the beginning of the line is matched by PATTERN and replace it with the string represented by SUBSTI
${var/%PATTERN/SUBSTI}:
Find the string represented by var to which the end of the line is matched by PATTERN and replace it with the string represented by SUBSTI
Note: use glob-style wildcards in PATTERN
For example:
] # userinfo= "root:x:0:0:root admin:/root:/binb/chroot"
] # echo ${userinfo/root/ROOT}: display: ROOT:x:0:0:root admin:/root:/binb/chroot; replacement for the first time
] # echo ${userinfo//r??t/ROOT}: display content: ROOT:x:0:0:ROOT admin:/ROOT:/binb/chROOT; replaces all
] # echo ${userinfo/#r??t/ROOT}: display content: ROOT:x:0:0:root admin:/root:/binb/chroot; line header replacement
] # echo ${userinfo/%r??t/ROOT}: display content: root:x:0:0:root admin:/root:/binb/chROOT; end-of-line replacement
Find and delete:
${var/PATTERN}: find the var string and delete only the string that was matched by PATTERN for the first time
${var//PATTERN}: find the var string and delete all strings matched by PATTERN
${var/#PATTERN}: find the string represented by var and delete only the string to which the beginning of the line is matched by PATTERN
${var/%PATTERN}: find the string represented by var and delete only the string to which the end of the line is matched by PATTERN
Character case conversion:
${var^ ^}: converts all lowercase characters in var to uppercase characters
${var,}: converts all uppercase characters in var to lowercase characters
For example:
] # url= "http://www.magedu.com:80"
] # echo ${URL ^ ^}: display content: HTTP://WWW.MAGEDU.COM:80; to uppercase:
] # myurl=$ {URL ^ ^}
] # echo ${myurl,}: display content: http://www.magedu.com:80; converted to lowercase
Variable assignment:
${var:-VALUE}: returns VALUE if the var variable is empty or is not set, otherwise, returns the value of the var variable
${var:=VALUE}: if the var variable is empty or not set, return VALUE and assign VALUE to the var variable, otherwise, return the value of the var variable
For example:
The variable hi is empty and has no defined value
] # echo ${hi:-world}: display content: world
] # hi= "hello"
] # echo ${hi:-world}: display content: hello
] # echo ${hi:=world}: display content: hello
] # unset hi: undo the value of the hi variable
] # echo ${hi:=world}: display content: world
] # echo $hi: the hi variable is assigned at this time
${var:+VALUE}: if the var variable is not empty, return VALUE;. Otherwise, it doesn't make sense.
${var:?ERRO_INFO}: if the var variable is empty or is not set, return ERRO_INFO as an error prompt; otherwise, return the value of var
Exercise: the script completes the following functions; (it must be completed, which will be used in subsequent course experiments)
(1) prompt the user for the name of an executable command
(2) get the list of all library files that this command depends on
(3) copy the command to the corresponding path under a directory (for example, / mnt/sysroot, that is, take this directory as the root)
Bahs,/bin/bash = > / mnt/sysroot/bin/bash
Usradd,/usr/sbin/useradd = > / mnt/sysroot/usr/sbin/usradd
(4) copy all the library files that this command depends on to the corresponding path under the directory.
/ lib64/ld-linux-x8664.so2 = > / mnt/sysroot/lib64/ld-linux-x8664.so.2
Further:
After each copy completes one command, do not quit, but prompt the user to continue to enter other commands to copy, and repeat the above function until the user enters "quit" to exit the script
Write a script: answer to the previous exercise
Use the ping command to detect whether all hosts in the range of 172.16.1.1-172.16.67.1 are online, online as up, and not online as down, and count the number of hosts respectively.
Implemented using for,while and until loops, respectively
Common way:
Declare-I uphosts=0
Declare-I downhosts=0
For i in {1... 67}; do
If ping-W 1-c 1 172.16.$i.1 & > / dev/null;then
Echo "172.16.$i.i is up"
Let uphosts+=1
Else
Echo "172.16.$i.1 is down"
Let downhosts+=1
Fi
Done
Echo "Up hosts: $uphosts,Down hosts: $downhosts"
Revision 2: function + while loop:
Declare-I uphosts=0
Declare-I downhosts=0
Declare-iionization 1
Hostping () {
If ping-W 1-c 1 $1 & > / dev/null;then
Echo "$i is up"
Let uphosts+=1
Else
Echo "$1 is down"
Let downhosts+=1
Fi
}
While [$I-le 67]; do
Hostping 172.16.$i.1
Let iTunes +
Done
Echo "Up hosts: $uphosts,Down hosts: $downhosts"
Revision 3: use return to count the number of hosts in ping in the main program
Declare-I uphosts=0
Declare-I downhosts=0
Declare-iionization 1
Hostping () {
If ping-W 1-c 1 $1 & > / dev/null;then
Echo "$i is up"
Return 0
Else
Echo "$1 is down"
Return 1
Fi
}
While [$I-le 67]; do
Hostping 172.16.$i.1
[$?-eq 0] & & let uphosts++ | | let downhosts++
Let iTunes +
Done
Echo "Up hosts: $uphosts,Down hosts: $downhosts"
Exercise: script implementation to detect whether all hosts in Class C, Class B, and Class A networks are online
Cping () {
Local iTunes 1
While [$I-le 245]; do
If ping-W 1-c 1 $1.Secreti & > / dev/null;then
Echo "$1.Secreti is up"
Else
Echo "$1.Secreti is down"
Fi
Let iTunes +
Done
}
# cping 192.168.0
Bping () {
Local jung0
While [$j-le 255]; do
Cping $1.10j
Let jacks +
Done
}
# bping 172.16
Aping () {
Local Xero0
While [$x-le 255]; do
Bping $1.0x
Let Xerox +
Done
}
Aping 10
Extension: the above script can be modified to prompt users to enter any network address or network address, get their network, and scan their network segments
All can ping this address, first determine the ip address category, and then call the corresponding function. For example, if the input is 10.0.0.1, cut out the first paragraph of the ip address to compare whether it is A (127,128191,192223), and then call the corresponding function implementation within their respective scope.
Signal capture of bash script programming
Trap command: just open the net to capture the signal on the first line of the script
Trap 'COMMAND' SIGANLS
-l: list signals
You can often capture signals: HUP, INT
COMMAND: you can use semicolons to separate multiple commands, or it can be a function
Note: the trap command cannot capture signals: 15-SIGTERM (terminal) and 9-SIGKILL (kill).
Because the main purpose of capturing a signal is to define what to do once the signal arrives, it may not be the default operation, so kill signals and other signals cannot be captured at will.
View the list of signals:
] # trap-l
] # kill-l
Check the signal type explanation:
] # man 7 signal
For example:
Trap 'echo "quit"; exit 1' INT
For i in {1... 254}; do
Ping 172.16.$i.1
Done
Example: using trp capture, function implementation
Ping172.16.1-254.1 saves the results in the temporary directory created under the / tmp/ directory, and then deletes those temporary files when you exit
This script cannot delete temporary files that were not captured last time.
Declare-a hosttmpfiles
Trap' mytrap' INT
Mytrap () {
Echo "quit"
Rm-f ${hosttmpfiles [@]}
Exit 1
}
For i in {1... 50}; do
Tmpfile=$ (mktemp / tmp/ping.XXXXX)
If ping-W 1-c 1 172.16.$i.1 & > / dev/null;then
Echo "172.16.$i.1 is UP" | tee $tmpfile
Else
Echo "172.16.$i.1 is down" | tee $tmpfile
Fi
Hosttmpfiles [${# hosttmpfiles [*]}] = $tmpfile
Done
Use ACSII colors in bash:
Format:\ 033 [front # landscape # color; back # landscape # color mSTRING\ 033 [0m]
\ 033 [#; # # mSTRING\ 033 [0m
Multiple controllers can be combined and separated by semicolons
\ 033 [31mhello\ 033 [0m
\ 033 [: indicates the control key Ctrl
\ 033 [0m: indicates the end of control
31m: represents the foreground color
Left digit: (foreground and background color can be set at the same time)
3: indicates the foreground color
4: represents the background color
Number on the right: indicates color
1: red
2: green
3: gold
4: blue
5: purple
6: cyan
7: Gray
For example:\ 033 [3mhello\ 033 [0m]
# m: indicates the font
1: bold
4: underline
5: flashing
7: front background reverse color
8: hidden
For example:
] # echo-e "\ 033 [31mhello\ 033 [0m": the foreground color is red
] # echo-e "\ 033 [41mhello\ 033 [0m": the background color is red
] # echo-e "\ 033 [41 × 32mhello\ 033 [0m": green foreground and red background
] # echo-e "\ 033 [7mhello\ 033 [0m": front background inverted
] # echo-e "\ 033 [4mhello\ 033 [0m": underlined
] # echo-e "\ 033 [42transfer35ter5mhello\ 033 [0m": green background, purple foreground, flickering
Built-in environment variable: PS1
Command line prompt format
The command line prompt format can be customized:
Export PS1=' [\ 033 [31m\ u\ 033 [0m @\ 033 [32m\ h\ 033 [0m\ 033 [35m\ W\ 033 [0m]\ $'
But after setting, there are side effects.
For example:
] # echo $PS1
Display content: [\ u@\ h\ W]\ $
Dialog command: (requires yum install installation)
Display dialog boxes from shell scripts
Dialog common-options box-options
Box-options:
There are three parameters: text, height, and width
-- calendar: calendar box
-- dselect: select the catalog box
-- editbox: edit box
-- form: form
-- gauge: progress bar
-- infobox: information box
-- inputbox: enter null
-- inputmenu: enter menu
-- menu: menu
-- msgbox: message box
-- passwordbox: password box, displayed as *
] # yum info dialog: check whether the dialog command has an installation package available
] # yum install dialog: install the dialog package
For example:
] # dialog-- msgbox hell 17 30: output message box 17 high and 30 wide
The dialog command enables windowing programming; some are implemented by calling curses in the C library.
Research:
Dialog command, how to use each form control
How do I get what the user selects or types? The default output of the dialog command is directed to the error output stream
Dialog $(dialog), the result should be saved in the variable, but cannot be assigned to the variable. You need to apply the option-- stdout in the variable command.
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.