Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summary of Bash Shell script programming Notes (1)

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article is a summary of class notes, involving the details of the knowledge will be explained in the future article!

Bash scripting:

Scripting: interpreter interpretation and execution

Shell: interactive interface; programming environment

Shell: can provide some internal commands and can find external commands through the PATH environment variable; submit commands to the kernel to start as a process

Programming environment:

Process control statement:

Sequential execution

Circular execution

Select execution

Conditional test: true or false

$?

The status result of the command:

0: true

1-255: false

Elements of a procedural programming language: variables, processes, functions, arrays

Variables: local variables, local variables, environment variables, location parameter variables, special variables

Variables:

Numeric type: integer, floating point, Boolean

Character type: string

Bash variable is weakly typed; default character type

Variable reference: ${VAR_NAME}

Quotation marks:

Weak reference: "

Strong quote:''

Command reference: ``

Declare a variable as an integer variable:

Let VAR_NAME=VALUEdeclare-I VAR_NAME=VALUE

Declare a variable as an environment variable:

Export VAR_NAME=VALUEdeclare-x VAR_NAME=VALUE

The format of the script:

The first line: write the interpreter; #! / bin/bash

Comment lines: all lines starting with # are comment lines; will be ignored by the interpreter

Execute the script:

Give execution authority; specify the path to execute

Pass the script directly to the bash interpreter

Options for bash:

-n: test if there are syntax errors in the script

-x: debug execution

Arithmetic operation:

$[EXPRESSION] let VAR_NAME=EXPRESSION$ ((EXPRESSION)) $(expr argu1 argu2 argu3)

One of the process controls: for cycle

Execute a piece of code repeatedly

Expression:

For VAR in LIST; doSTATEMENT1...done

For VAR in LIST; do statement1; statement2;...; done

For ((initialize loop control variable; loop condition; modified expression); do loop body done

Condition of entry; condition of exit

Cyclic body; STATEMENT1

Sleep: sleep [n]

Number of loops: the number of elements in the list

LIST: list, a collection of strings containing at least one element

(1) give directly

(2) list of values:

(a) {start..end}

For example: {1. 10}

(B) seq [start [step]] end

Seq LASTseq FIRST LASTseq FIRST STEP LAST

(3) the command that returns the list

(4) globbing

(5) variable reference

$*, $@

For example: add 3 users, user1, user2, user3; password is the same as user name

# vi useradd.shrunken usernamedone bind Bash for username in user1 user2 user3; douseradd $usernameecho $username | passwd-- stdin $usernamedone

For example: add 9 users, and user101...user109; password is the same as user name

# vi useradd2.shbind bind in for I Bashfor {1.. 9}; douseradd user10 $iecho user10 $I | passwd-- stdin user10 $idone

Exercise: create 10 empty files F1, f10 in the / tmp/test directory

# vi addfile.shantilash directoryfor i in binapachebashdirectoryhelplash TMP Universe $(date'+% Y% m% h') mkdir $directoryfor i in {1.. 10}; bash $directory/f$idone

Exercise: write a script

(1) create "/ tmp/test- current time" directory

(2) add 10 users tuser1,.., tuser10

(3) in the "/ tmp/test- current time" directory, create 10 empty files f1pm.

(4) modify the owner of F1 to tuser1;, and so on.

# vi creatdir.shangxinxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Exercise: find the sum of all positive integers within 100

# vi plus.shrousashashbinram bashsummation 0for I in `doneecho 100`; dosum=$ (($sum+$i)) doneecho $sum

Exercise: find the sum of all even numbers within 100; and the sum of all odd numbers

#! / bin/bashdeclare-I sum=0for I in `seq 1 2100`; do sum=$ (($sum+$i)) doneecho $sumdeclare-I sum1=0for I in `seq 2 2100`; do sum1=$ (($sum1+$i)) doneecho $sum1 exercise 5: calculate the sum of all users'ID on the current system; #! / bin/bashsum=0for I in `cut-d:-f3 / etc/ passwd`; do sum=$ (($sum+$i)) doneecho $sum

Exercise: pass parameters (text file path) to the script to count the sum of blank lines in all files; show how many files are counted this time

#! / bin/bashsum=0num=0echo $# for i in `seq 1 $# `; do num= `grep'^ $'$1 | wc-l` sum=$ (($num+$sum)) shiftdoneecho $sum

Exercise: display the total number of all users on the current system whose default shell is bash, and count the sum of these users'ID

For id in `grep "/ bin/bash$" / etc/passwd | cut-d:-f3`; do

#! / bin/bashsum=0num=0for I in `grep 'bash$' / etc/passwd | cut-d:-f3`; do sum=$ (($sum+$i)) num=$ (($num+1)) done

Several special cases of for:

(1) omitted by for, the script parameter list will be obtained automatically.

(2) C programming style:

For ((variable assignment; cyclic condition; modified expression); do

CMD1

CMD2

Done

(3) Loop nesting:

For i in [LIST1]; do

CMD1

For j in [LIST2]; do

CMD2

...

Done

Done

Exercise: write a script

(1) all hosts in the ping 172.16.X.Y

172.16.0-255.1-254

For i in {0.255}; do for j in {1... 254}; do ping-C1-w1 172.16.$i.$j donedone

Exercise: write a script

(1) pass some directories to the script

(2) display the content types of all first-level files in each directory one by one

(3) count how many directories there are and how many files are displayed

#! / bin/bash#declare-I dirs=0declare-I files=0for d in $*; do for f in $d files; do file $f let files++ done let dirs++doneecho "Directories: $dirs." echo "Files: $files."

Bash command exit and exit status code

When a command exits after execution in bash, the success of its execution can be recorded by the exit status code.

# echo $?

The exit status code of the script depends on the last command executed; custom exit status code:

Exit #

Success: 0

Failure: 1-255

#! / bin/bashls / varrretval=$?echo 'hello'exit $retvel

The exit status is based on the result status of ls / varr

Note: exit the script early, or you can use the exit command to do so

Conditional testing for bash scripting:

If/then structure

Conditional testing:

Test EXPRESSION [EXPRESSION] [[EXPRESSION]]

COMMAND: command exit status code is used

1. Execute the result using the command

a. Use command reference

b. Use the comparison operator

For example:

[`id-u $username`-lt 500] userid= `id-u $username` [$userid-lt 500]

two。 Use the exit status code of the command

a. Run the command first

b. Reference status code

There are two ways to quote:

1.if COMMAND & > / dev/null;then

The reference is the exit status code of the command run

Note: COMMAND cannot be referenced by commands, and the execution result of COMMAND is usually meaningless, so the result is usually directed to / dev/null

two。 Execute the command first, and then determine whether the exit status code is 0.

COMMAND

Retval=$?if [$?-eq 0]; then

Test expression:

(1) Integer test; for example: 1 B

A

< B A >

= B

A / dev/null;then condition reverses useradd $1fifi

The following steps of then can only be performed if the if condition is determined to be true.

If the status of id $1 is 0, the execution status is successful. If the inverse condition is false, then will not execute it.

If the execution status of id $1 is 1, it indicates that the execution status is failed. If the condition judgment is true after inversion, then starts execution.

Exercise: write a script

(1) add user testuser1-tuser10

(2) add only when the user does not exist

(3) Statistics on the number of users really added

#! / bin/bash#declare-I newusers=0for I in {1... 10}; do if! Id testuser$i & > / dev/null; then useradd testuser$i let newusers++ fidoneecho "New users: $newusers."

Exercise: write a script

(1) use the ping command to test all hosts in 172.16.100.X

(2) output the online host

#! / bin/bash#for I in {1.. 254}; do if ping-C1-W1 172.16.100.Secreti & > / dev/null; then echo "172.16.100.Secreti is up." Fidone

Double branch structure:

If CONDITION-TRUE; then Branch 1else Branch 2fi

Exercise 1: write a script

(1) use the ping command to test all hosts in 172.16.100.X

(2) output the online status of all hosts

#! / bin/bashfor I in {1.. 254} doif ping-C1-W1 172.16.100.Secreti & > / dev/null;thenecho "172.16.100.Secreti is up" elseecho "172.16.100.Secreti is down" fidone

Exercise: write a script

(1) pass two integer parameters to the script

(2) return the larger one

#! / bin/bashdeclare-I max=0for I in $*; doif [$I-gt $max]; thenmax=$ifidoneecho $max

Exercise: write a script

(1) pass more than two integers to the script

(2) return to the larger

#! / bin/bash#declare-I max=0for I in $*; do if [$I-gt $max]; then max=$i fidoneecho "max: $max."

Exercise: write a script

(1) get the current hostname

(2) if the current hostname is localhost, change it to oracle;. Otherwise, display its name.

#! / bin/bashhostname= `hostname`if ["$hostname" = = 'localhost']; then hostname oracle echo "oracle" > / proc/sys/kernel/hostnamefi

Exercise: write a script

(1) pass two text file paths to the script

(2) display the files with more blank lines in the two files and the number of blank lines

(3) display the files with a large number of lines in the two files and their number of lines

#! / bin/bashif [$#-ge 2]; then if [[$(wc-l $1 | cut-d ""-F1)-gt $(wc-l $2 | cut-d ""-F1)]]; then if [[$(grep "^ $" $1 | wc-l)-gt $(grep "^ $" $2 | wc-l)]] Then echo "the more space line file is $1" echo "the file space line is $(grep" ^ $"$1 | wc-l)" else echo "the more space line file is $2" echo "the file space line is $(grep" ^ $"$2 | wc-l)" Fi echo "the more line file is $1" echo "the line have $(wc-l $1)" else echo "the more line file is $2" echo "the line have $(wc-l $2)" fifi

Exercise: write a script

(1) pass a parameter to the script, which is the user name

(2) if the user exists, perform the following tasks

(a) if the user's id number is less than 500, it indicates that the user is an administrator or a system user

(B) otherwise, show that it is an ordinary user

(3) if the user does not exist, add it

#! / bin/bash#if id $1 & > / dev/null; then userid= `id-u $1`if [$userid-lt 500]; then echo "$1 is sysadmin or sysuser." Else echo "A common user." Fielse useradd $1 if [$?-eq 0]; then echo "Add user $1." Else echo "Cannot add $1." Fifi

Multi-branch if statement:

If CONDITION1-TRUE; then Branch 1elif CONDITION2-TRUE; then Branch 2elif CONDITION3-TRUE; then Branch 3...else Branch nfi

Exercise: pass a parameter to the script

If the parameter is quit, it shows that you want to exit the script

If the parameter is yes, it says continue.

Otherwise, it is displayed as unrecognized

#! / bin/bashif [["$1" = = 'quit']]; thenecho "quit" elif [["$1" = =' yes']]; thenecho "yes" else echo "unkown" fi

Exercise: pass a username parameter to the script

(1) if the user's id number is 0, it will be displayed as an administrator

(2) if the user's id number is greater than 6000, it will be displayed as guest

(3) if the user's id number is greater than 500, it will be displayed as an ordinary user.

(4) if the user's id number is greater than 0, it will be displayed as the system user.

(5) otherwise, it cannot be recognized

#! / bin/bashif id $1 & / dev/null; thenuserid= `id-u $1`if [$userid-eq 0]; thenecho "$1 is sysadmin" elif [$userid-gt 60000]; thenecho "$1 is a guest user" elif [$userid-gt 60000]; thenecho "$1 is a common user" elif [$userid-gt 0]; thenecho "$1 is a system user" elseecho "$1 is unknown" fi

Exercise 3: write a script

(1) pass a disk device file to the script

(2) determine whether the device exists; if so, clear all partitions on the device

(3) otherwise, there is no such equipment.

#! / bin/bashif fdisk-l $1; thendd if=/dev/zero of=$1 bs=512 count=1elseecho "no such device" fi

Combined test condition 1:

Add a logical operator to a condition

Or,-o: [- z "$hostname"-o "$hostname" = 'localhost']

With,-a: [$uid-gt 0-a $uid-lt 500]

Non: [! EXPRESSION]

Exercise: write a script, get the current hostname, and determine

(1) if the hostname is empty or "localhost", name it stuX.oracle.com

(2) otherwise, the hostname can be displayed

#! / bin/bash#hostname= `hostname`if ["$hostname" = = 'localhost'-o-z "$hostname"]; then hostname stu100.oracle.com # echo "stu100.oracle.com" > / proc/sys/kernel/hostnameelse echo "The hostname is: $hostname." fi

Exercise: write a script and pass a parameter to the script; this parameter is the user name

(1) if the user does not exist, exit the script directly

(2) if the user exists

Id=0, is displayed as "system admin"

0 / dev/null; then echo "No such user." Exit 1fiuidroads $(id-u $1) if [$uid-eq 0]; then echo "Sys Admin." elif [$uid-gt 0-a $uid-lt 500]; then echo "Sys User." else echo "Common User." fi

Exercise: write a script and pass a parameter to the script; this parameter is the user name

(1) if the user does not exist, exit the script directly

(2) if the user's id number is greater than or equal to 500 and its shell is "ending in sh" type, "a user can log system." is displayed; otherwise, it shows that the user cannot log in.

#! / bin/bash#if! Id $1 & > / dev/null; then echo "No such user." Exit 1fiif [[``grep-u $1`-ge]] & [[``grep "^ $1\ >" / etc/passwd | cut-d:-f7` = ~ / bin/.*sh$]]; then echo "a user can log system." else echo "a user cannot log." fi

Combined test condition 2:

Short circuit operator

And: COMMAND1 & & COMMAND2

If the exit status of COMMAND1 is false, then COMMAND2 can have the final result without running it.

Or: COMMAND1 | | COMMAND2

If the exit status of COMMAND1 is true, COMMAND2 can have the final result without running it.

Non:! COMMAND

[!-d / tmp/test] & & mkdir / tmp/ test ^ C [- d / tmp/test] | | mkdir / tmp/test

Exercise: write a script to complete the following tasks:

(1) if the httpd process or nginx process is running, "web server started." is displayed and the port on which it listens is displayed.

(2) otherwise, "no web server."

If pidof httpd & > / dev/null & & pidof nginx & > / dev/null

Interactive scripts:

Read [OPTIONS] [name...]

-p "PROMPT"

-t #: timeout length

Give the variable the default value:

[- z "$VAR"] & & VAR=VALUE

Exercise: display the following menu to the user

Cpu) show cpu infomation

Mem) show memory infomation

Disk) show disk infomation

*) quit

Prompt the user for options:

(1) cpu: displays information related to CPU

(2) mem: displays memory-related information

(3) disk: list disk devices

(4) any other information is the exit script.

#! / bin/bash#cat / dev/null status=$?doneecho "centos is logged on."

Method 2: simplified version

#! / bin/bash#declare-I status=0until who | grep "centos" & > / dev/null; do sleep 5doneecho "centos is logged on."

Method 3: use an endless loop

#! / bin/bash#while true; do who | grep "centos" & > / dev/null if [$?-eq 0]; thenbreak fi sleep 5doneecho "centos is logged."

Special use of while: traversing every line of a specified file

While read line; do

Cyclic body

Done

< /path/from/somefile 练习:找出其UID为偶数的所有用户的用户名;并显示其ID号; #!/bin/bash#file=/etc/passwdwhile read line; do userid=`echo $line | cut -d: -f3` if [ $[$userid%2] -eq 0 ]; thenecho $line | cut -d: -f1,3 fidone < $file 练习:输出给定的文件的偶数行的行号,以及其行内信息统统改为大写字母输出; #!/bin/bashdeclare -i i=1while read line; do if [ $[$i%2] -eq 0 ]; then echo -n "$i " echo $line | tr 'a-z' 'A-Z' fi let i++done < /path/from/somefile 练习:显示如下菜单给用户 cpu) cpuifno mem) memory infomation disk) disk infomation quit) quit (1) 用户给定的选项后,显示相应的信息;而后提示用户再次选择; (2) 非正确选择也提示用户重新选择,并说明,如果想退出请输入"quit"; #!/bin/bash#while true; docat /dev/null && return 2 grep "^$1\>

"/ etc/passwd | cut-d:-f7 [$?-eq 0] & & return 0 | | return 3} while true; do read-p" Enter a username: "username [" $username "= = 'quit'] & & break showuserinfo $username [$?-ne 0] & & echo" There is something wrong. "done

Exercise: use function to print 99 multiplication table

#! / bin/bashfunc () {declare i=1declare j=1while [$I-le 9]; do while [$j-le 9]; do if [$j-gt $I] Then break fi echo-e-n "{$j} xroomibj]\ t" let jungle + done echo let juni1 let iTunes + done} func

Exercise: write a script to perform the following functions (using functions):

1. Prompt the user for an executable command

2. Get all the library files on which this command depends (using the ldd command)

3. Copy the command to the directory corresponding to / mnt/sysroot/

Explanation: suppose that if you copy the cat command and its executable path is / bin/cat, then copy / bin/cat to the / mnt/sysroot/bin/ directory. If you copy the useradd command and the executable path of useradd is / usr/sbin/useradd, copy it to the / mnt/sysroot/usr/sbin/ directory.

4. Copy the library files to the corresponding directory of / mnt/sysroot/

#! / bin/bash#target=/mnt/sysroot [- d $target] | | mkdir $targetpreCmd () {if which $1 & > / dev/null Thencmdpath=$ (which-- skip-alias $1) return 0 elseecho "No such command." return 1 fi} cmdCopy () {cmddir=$ (dirname $cmdpath) [- d $target/$cmddir] | | mkdir-p $target/$cmddir [- f $target/$cmdpath] | | cp $1$ target/$cmddir return 0} libCopy () {for lib in $(ldd $1 | grep-E-o "/ [^ [: space:]] +") Dolibdir=$ (dirname $lib) [- d $target/$libdir] | | mkdir-p $target/$libdir [- f $target/$lib] | | cp $lib $target/$libdir done return 0} main () {while true; do read-p "Plz enter a command (quit for quiting):" cmd ["$cmd" = = 'quit'] & & break preCmd $cmd if [$?-eq 0]; then cmdCopy $cmdpath libCopy $cmdpath fi done} main

Scope of the variable:

Local variables: the entire script can also be called or modified in the function of the script

Local variables: the entire life cycle of a function call

Local VAR=VALUE

Function recursion:

The function calls the function itself directly or indirectly

1 1 2 3 5 8 13

Factorial: 10!

N (nmur1)!

N (nmur1) (nmur2)!

Factorial function:

Fact () {

If [$1-eq 0-o $1-eq 1]; then

Echo 1

Else

Echo $[$1mm $(fact $[$1-1])]

Fi

}

The next article follows: summary of Bash Shell script programming notes (2)

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.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report