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

6.3 bash programming character testing

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Given a user, determine whether its UID and GID are the same "^ $USERNAME\ >" (the first word at the beginning of the line)

If the same, the user is shown as "good guy"; otherwise, the user is shown as "bad guy"

#! / bin/bash

#

USERNAME = user1

If! grep "^ $USERNAME\ >" / etc/passwd & > / dev/null;then user does not exist

Echo "No such user: $USERNAME."

Exit 1

Fi

USERID = `USERNAME` USERID-u $USERNAME`

GROUPID = `USERNAME` GROUPID-g $USERNAME`

If [$USERID-eq $GROUPID]; then

Echo "good guy"

Else

Echo "bad guy"

Fi

Exit: exit script

Exit # (# for numbers)

Three kinds of conditional testing commonly used in bash

-gt

-le

-ne

-ge

-lt

-non-zero values of eq are false.

-[] can only be used above, and [] cannot appear in other expressions.

INT1 = 63

INT2 = 77

[$INT1-eq $INT2]

[[$INT1-eq $INT2]]

TEST $INT1-eq $INT2

If [`grep "^ $USENAME\ >" / etc/passwd | cut-d:-f3`-eq 0]; then pair

If [`grep "^ $USENAME\ >" / etc/passwd `- eq 0]; then error (preceded by a line)

Testing method

[expression] commands of bash

`expression `bash keyword

Test expression

File testing:

-e FILE: test whether a file exists

-f FILE: test whether the file is a normal file

-d FILE: tests whether the specified path is a directory

-r FILE: tests whether the current user has read access to the specified file

-w

-x FILE

[- e / etc/initttab]

[- x / etc/rc.d/rc.sysinit]

Exercise: write a script

Given a file, such as / etc/inittab

Determine if there are blank lines in this file

If so, the number of blank lines is displayed, otherwise, there are no blank lines

#! / bin/bash

FILE = / etc/inittab

If [!-e $FILE]; then

Echo "No $FILE."

Exit 8

Fi

If grep "^ $" $FILE & > / dev/null;then

Echo "Total blank lines: `grep" ^ $"$FILE | wc-l`."

Else

Echo "No blank line."

Fi

Round, discarding the content after the decimal point

The expr command is generally used for integer values

# expr argument operator argument

Exercise: write a script

Given a user, get its password warning period:

Then judge whether the last time the user changed the password has been less than the warning period.

Hint: the method of arithmetic operation $[$Amurables B]: represents the result of the value of variable A minus the value of variable B.

If less than, "Warning" is displayed; otherwise, "OK" is displayed

#! / bin/bash

#

W = `grep "student" / etc/shadow | cut-d:-f6`

S = `date +% s`

T = `expr $S/ 86400`

L = `grep "^ student" / etc/shadow | cut-d:-f5`

N = `grep "^ student" / etc/shadow | cut-d:-f3`

SY=$ [$Lmure $[$Tmurf]]

If [$SY-lt $W]; then

Echo 'Worning'

Else

Echo 'OK'

Fi

Exercise: write a script

Determine whether the total entries of historical commands in the command history are greater than 1000; if so, display

"Some command will gone."; otherwise display "ok"

The number of entries in the history current display buffer (will be greater than 1000)

$HISTSIZE only shows 1000.

$HISTFILESIZE only shows 1000.

History | tail-l | cut-d''- F1, the number of entries cannot be obtained because there is a space in front of it, so the second field should be selected.

History | tail-l | cut-d'-f2

#! / bin/bash

#

COUNT = history | tail-l | cut-D''- f2

If $COUNT-gt 1000; then

Echo "Some command will gone."

Else

Echo "ok"

Fi

Multi-branch if statement

If judgment condition 1 then yes

Statement1

...

Elif judgment condition 2then

Statement2

...

Elif judgment condition 3then yes

Statement3

...

Else judgment condition 4then yes

Statement4

...

Fi

#! / bin/bash

#

FILE = / etc/inittab

If [- e $FILE]; then

Echo "OK"

Else

Echo "No such file"

Fi

Test the script for syntax errors

Bash-n filetest.sh

Bash-x script: step through

Given a file, if it is an ordinary file, display it

If it is a catalog, it also shows

Otherwise, this is an unrecognized file

Filetest2.sh

#! / bin/bash

#

FILE = / etc/rc.d/rc.sysinit

If [!-e $FILE]; then

Echo "NO such file"

Exit 6

Fi

If [- f $FILE]; then

Echo "Common file"

Elif [- d $FILE]; then

Echo "Directory"

Else

Echo "Unkown."

Fi

Define script exit status code

If the script does not clearly define the exit status code, the last command executed

The exit code is the exit status code of the script

Type of bash variable:

Local variables (local variables) current shell process

Environment variables current shell process and its child processes

Location variable: $1 $2.

Shift (kicks off a position value) 1 kick by default

Shift [n] kicked out n

Special variable $?

$#: number of parameters

$*: parameter list

$@: parameter list

. / filetest.sh / etc/fstab / etc/inittab

$1:/etc/fstab

$2:/etc/inittab

Exercise: write a script

Can accept one parameter (file path)

Decision: if this parameter is an existing file, OK is displayed, otherwise No such file is displayed.

#! / bin/bash

#

Echo $#

Echo $*

Echo $@

If [$#-lt 1]; then

Echo "Usage:. / filetest3.sh ARG1 [ARG2...]"

If [- e $1]; then

Echo "ok"

Else

Echo "No such file"

Fi

Exercise: write a script

Pass two parameters (integers) to the script

Show the product of the sum of these two parameters

#! / bin/bash

#

If [$#-lt 2]; then

Echo "Usage: cac1.sh ARG1 ARG2"

Exit

Fi

Echo "The sum is: $[$1 + $2]."

Echo "The prod is: $[$1 * $2]."

Sed-n silence

-I modify the original file directly

-e SCRIPT-e SCRIPT: multiple scripts can be executed simultaneously

-f / PATH/TO/SED_SCRIPT

Sed-f / path/to/scripts file

This file is a script line and a script is used on file.

-r: indicates the use of extended regular expressions

Delete the space at the beginning of the line

History | sed's # ^ [[: space:]] * # # g'

History | sed's # ^ [[: space:]] + # # g'

G: global replacement

I: ignore character case

Scanplet Uniplus.Sigma raceme raceme racquettes.

Sed's rooml... is responsible for ringing sed.txt.

Item reference after sed's #\ (l.. e\) #\ 1rsigg' sed.txt

Like-Like

Love-Love

Sed's sed.txt\ (.. e\) # L\ 1

&: the entire string to which the reference pattern is matched

Sed activity:

1 remove the blank character at the beginning of the line in the / etc/grub.conf file

Sed-r's @ ^ [[: space:]] + @ @ g' / etc/grub.conf

2 replace the line "id:3:initdefault:" in the / etc/inittab file

The number in is 5

Sed's @\ (id:\) [0-9]\ (: initdefault:\) @\ 15\ 2 initdefault'/ etc/inittab

3 remove blank lines in / etc/inittab file

Sed'/ ^ $/ d' / etc/inittab

4 Delete the initial # in the / etc/inittab file

Sed's @ ^ # @ @ g' / etc/inittab

5 remove the # sign followed by the white space character in the / etc/inittab file, but it is required

The # sign must be followed by a white space character

Sed-r's @ ^ # [[: space:]] + @ @ g' / etc/inittab

6. Delete a file that begins with a white space character followed by a line of class #

White space character and #

Sed-r's @ ^ [[: space:]] + @ @ g' / inittab

7 take out the directory name of a file path

Echo "/ etc/rc.d/" | sed-r's @ ^ (/. * /) [^ /] + /? @\ 1Secretg' to fetch etc

Base name:

Echo "/ etc/rc.d/" | sed-r's @ ^ /. * / ([^ /] +) /? @\ 1Secretg' to fetch rc.d

# abc

# hello world

# hi world

Exercise:

Pass a user name parameter to the script to determine that the user name is the same as the

Whether the group name is the same, and display the result

[] the condition is

Vi testUser.sh

#! / bin/bash

#

If! id $1 & > / dev/null;then

Echo "No such user."

Exit 8

Fi

# if [`id-n-u $1` = = `id-n-g $1`]; then

If [$1 = = `id-n-g $1`]; the then user name is already a string

Echo "yiyang"

Else

Echo "buyiyang"

Fi

Character test:

= [$A = $B]

! = [$A! = $B]

>

> / tmp/testusers

Exercise:

Determine the CPU manufacturer of the current host, whose information is vendor id in / proc/cpuinfo file

In one line, if its manufacturer is AuthenticAMD, it is shown to be AMD; if it is born

If the manufacturer is GenuineIntel, it shows that it is Intel: otherwise, it is said to be non-mainstream.

Company:

Write a script:

Pass three parameters to the script, judge the maximum and minimum, and display them.

MAX=0

-eq-lt

Write a script:

1 set the value of the variable FILE to / etc/passwd

2 say hello to each user in / etc/passwd in turn and display each other's shell, such as:

Hello,root,your shell:/bin/bash

3 count the total number of users

LINES = `wc-l / etc/passwd | cut-d''- f1`

For I in `seq 1$ LINES`; do

Echo "hello, `head-n $I / etc/passwd | tail-1 | cut-d:-f1`"

Only say hello to users whose default shell is bash

Write a script:

1 add 10 users user1 to user10, but only if the user does not exist

Add, password same as user name

Extend:

Receive a parameter

Add: add user user1..user10

Del: delete user user1..user10

Others, quit.

Adminusers-add user1,user2,user3,hello,hi

Vim adminuser2.sh

# / bin/bash

#

# echo $1

# echo $1 | tr-dumbjue 'delete all commas

# echo $1 | sed's Grammar / / g'

For I in `echo $1 | sed's Universe / / g'`; do

If id $I & > / dev/null;then

Echo "$I exist."

Else

Useradd $I

Echo $I | passwd-- stdin $I & > / dev/null

Echo "add $I finished."

Fi

Done

Vim adminuser3.sh

# / bin/bash

#

If [$1 ='--add']; then

For I in `echo $2 | sed's Universe / / g'`; do

If id $I & > / dev/null;then

Echo "$I exist."

Else

Useradd $I

Echo $I | passwd-- stdin $I & > / dev/null

Echo "add $I finished."

Fi

Done

Elif [$1 ='--del']; then

For I in `echo $2 | sed's Universe / / g'`; do

If id $I & > / dev/null;then

Userdel-r $I

Echo "Delete $I finished."

Else

Echo "$I not exist."

Fi

Done

Elif [$1 ='--help']

Echo "Usage:adminuser2.sh-- add USER1,USER2,... |-- del USER1,USER2,...-- help"

Else

Echo "Unkown ARG"

Exit 8

Fi

In the remaining three months, you are willing to be a partner with learning, rich or poor

No matter computer or mobile phone, no matter how sleepy or tired you are, whether you want to eat or sleep.

We should give priority to study, aim at not falling behind, and share joys and sorrows.

Never give up, cherish her, respect her, understand her, protect her, are you willing to do so?

Vim adduser.sh

#! / bin/bash

#

For I in {1... 10}; do

If id user$I & > / dev/null;then

Echo "user$I exist."

Else

Useradd user$I

Echo user$I | passwd-- stdin user$I & > / dev/null

Echo "ADD user user$I finished"

Fi

Done

Vim deluser.sh

#! / bin/bash

#

For I in {1... 10}; do

If id user$I & > / dev/null;then

Userdel-r user$I

Echo "Delete user$I finished."

Else

Echo "user$I not exist."

Fi

Done

Vi adminnusers.sh

# / bin/bash

#

If [$#-lt 1]; then

Echo "Usage:adminnusers ARG"

Exit 7

Fi

If [$1 ='--add']; then

For I in {1... 10}; do

If id user$I & > / dev/null

Echo "user$I exist."

Else

Useradd user$I

Echo user$I | passwd-- stdin user$I & > / dev/null

Echo "ADD user user$I finished"

Fi

Done

Elif [$1 ='--del']; then

For I in {1... 10}; do

If id user$I & > / dev/null;then

Userdel-r user$I

Echo "Delete user$I finished."

Else

Echo "user$I not exist."

Fi

Done

Else

Echo "Unkown ARG"

Exit 8

Fi

Cycle: entry condition, exit condition

For

While

Until

For variable in list; do

Cyclic body

Done

For i in 1 2 3 4 5 X do

Addition operation

Done

When the traversal is complete, exit:

How to generate a list:

{1..100}

Seq [start [step length]] end number

`ls / etc` can also access the list of each file

The default variable is a string

Declare-I SUM=0

Integer

-x (environment variable)

1,...100

# / bin/bash

#

# let SUM = 0 now the variable is the numeric let

Declare-I SUM=0

For I in {1... 100}; do

Let SUM = $[$SUM+$I]

Done

Echo "The sum is $SUM."

Write a script

Calculate the sum of all integers divisible by 3 within 100

Take the mold, take the rest%

Write a script:

Calculate the sum of all odd numbers within 100 and the sum of all even numbers: show them respectively:

Write a script that displays all users on the current system whose default shell is bash and the default

Shell is / bin/nologin users, and statistics of the total number of users under all kinds of shell, display

The result is as follows:

BASH,3users,they are:

Root,redhat,gentoo

NOLOGIN,2users,they are:

Bin,ftp

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: 273

*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

Internet Technology

Wechat

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

12
Report