Linux Shell advanced skills (3)

Source: Internet
Author: User
Tags egrep

13. Format and output the current running process of the specified user:

In this example, we pass the user list to the script in the form of Script Parameters. After the script reads the parameters, print the process of the user in the user list in the form of a tree.
/> CAT> test13.sh
#! /Bin/sh
#1. Read the Script Parameters cyclically and construct user list variables that can be recognized by egrep (based on the grep extension regular expression ).
 #2. If the userlist variable has not been assigned a value, use the first parameter to assign a value to it.
#3. if a value has been assigned and multiple users exist in the script parameter, a vertical line must be added between each user name. In egrep, the vertical line is the relationship between the separated elements or.
#4. Shift the command to move the location parameter of a script to the left, so that the first parameter can always be operated in the loop.
While [$ #-GT 0]

Do
If [-z "$ userlist"]; then
Userlist = "$1"
Else
Userlist = "$ userlist | $1"
Fi
  Shift
Done
#5. If there is no user list, search for all user processes.
#6. "^ * ($ userlist)": the following call method. The regular expression is expanded in the form of "^ * (root | avahi | Postfix | RPC | timeout )". It indicates that it starts with 0 or multiple spaces and is followed by any character string in root, avahi, Postfix, RPC, or callback, followed by a space.
If [-z "$ userlist"]; then
Userlist = "."
Else
Userlist = "^ * ($ userlist )"
Fi
#7. The ps command outputs the user and command information of all processes, passes the result to the SED command, and sed deletes the title part of PS.
#8. egrep filters all process records that contain the specified user list, and then passes the filtered results to the sort command.
#9. The-B option in the SORT command ignores leading spaces and sorts the result by user and process name. A uniq command is passed.
#10. The uniq command combines duplicate records. The-C option will add the number of duplicated rows before each record.
#11. The second sort will be sorted again, first by user, then by repeated count from large to small, and finally by process name. Send the result to the awk command.
#12. The awk command format the data and delete duplicate users.
PS-EO user, comm | sed-e 1D | egrep "$ userlist" |
Sort-B-K1, 1-K2, 2 | uniq-c | sort-B-K2, 2-k1nr, 1-K3, 3 |
Awk '{user = (lastuser = $2 )? "": $2;
Lastuser = $2;
Printf ("%-15s \ t % 2D \ t % s \ n", user, $1, $3)
}'
CTRL + d
/>./Test13.sh root avahi Postfix RPC restart
Avahi 2 avahi-daemon
When 1 then-daemon
Postfix 1 pickup
1 qmgr
Root 5 mingetty
3 udevd
2 sort
2 sshd
......
RPC 1 rpcbind

14. Use a script to complete the basic functions of the which command:

We often call other applications in scripts. Program To ensure better robustness of the script and accuracy of error prompts, we may need to verify whether the command exists or can be executed before execution. First, check whether the command is in the Directory included in the PATH variable, and then whether the file is executable.
/> CAT> test14.sh
#! /Bin/sh
#1. This function is used to determine whether the command in parameter 1 is in the directory list contained in parameter 2. It should be noted that $1 and $2 in a function refer to the function parameters, rather than the script parameters.
#2. cmd = $1 and Path = $2. It is a good habit to assign a parameter to a meaningful variable name.
#3. Because the delimiter between directories in the PATH environment variable is a colon, You need to temporarily set IFS to a colon here, and then restore after the function is complete.
#4. In the for loop, locate the directories in the variable directory list one by one to determine whether the command exists and is an executable program.
Isinpath (){
Cmd = $1 Path = $2 result = 1
Oldifs = $ ifs = ":"
For dir in $ path
Do
If [-x $ DIR/$ cmd]; then
Result = 0
Fi
Done
Ifs = oldifs
Return $ result
}
#5. check whether the main function of the command exists. First, determine whether it is an absolute path, that is, whether the first character of the $ var variable is/. If yes, then determine whether it has executable permissions.
#6. If it is not an absolute path, use the isinpath function to determine whether the command is in the directory specified by the PATH environment variable.
Checkcommand (){
Var = $1
If [! -Z "$ Var"]; then
If ["$ {var: 0: 1}" = "/"]; then
If [! -X $ var]; then
Return 1
Fi
Elif! Isinpath $ var $ path; then
Return 2
Fi
Fi
}
#7. verify the validity of script parameters.
If [$ #-ne 1]; then
Echo "Usage: $0 command"> & 2;
Fi
#8. Print different information based on the returned value. Here we can complete different tasks based on our needs.
Checkcommand $1
Case $? In
0) echo "$1 found in path .";;
1) echo "$1 not found or not executable .";;
2) echo "$1 not found in path .";;
Esac
Exit 0
CTRL + d
/>./Test14.sh echo
Echo found in path.
/>./Test14.sh mytest
Mytest not found in path.
/>./Test14.sh/bin/mytest
/Bin/mytest not found or not executable.

15. Verify that the input information is valid:

The example here is to verify whether all the information entered by the user is numbers and letters. It should be noted that the reason for collecting it into this series is mainly because it is implemented in a clever way.
/> CAT> test15.sh
#! /Bin/sh
Echo-n "Enter your input :"
Read Input
#1. In fact, the clever thing here is to replace the illegal part with SED, and then compare the replaced result with the original string. This method is also easy to expand.
Parsed_input = 'echo $ input | SED's/[^ [: alnum:] // g''
If ["$ parsed_input "! = "$ Input"]; then
Echo "your input must consist of only letters and numbers ."
Else
Echo "input is OK ."
Fi
CTRL + d
/>./Test15.sh
Enter your input:Hello123
Input is OK.
/>./Test15.sh
Enter your input: Hello World
Your input must consist of only letters and numbers.

16. Integer Verification:

An integer contains numbers 0 to 9 and minus signs (-).
/> CAT> test16.sh
#! /Bin/sh
#1. Determine whether the first character of the variable number is a negative sign (-). If only the value is "-", delete the negative number and assign the deleted result to the left_number variable.
#2. for the meanings of "$ {number #-}", refer to "Linux Shell common tips (11)" In this blog series and search for the keyword "variable pattern matching operator.
Number = $1
If ["$ {number: 0: 1}" = "-"]; then
Left_number = "$ {number #-}"
Else
Left_number = $ number
Fi
#3. replace all the numbers in the left_number variable. Therefore, if the returned string variable is null, it indicates that the characters in the left_number are numbers.
Nodigits = 'echo $ left_number | SED's/[[: digit:] // g''
If ["$ nodigits "! = ""]; Then
Echo "Invalid Number Format! "
Else
Echo "you are valid number ."
Fi
CTRL + d
/>./Test16.sh-123
You are valid number.
/>./Test16.sh 123e
Invalid Number Format!

17. Determine whether the specified year is a leap year:

Here we will first list the rules for a leap year:
1. The year that cannot be divisible by 4 must not be a leap year;
2. The year that can divide 4 and 400 at the same time must be a leap year;
3. It can be divided into 4 and 100, but not 400 years, not a leap year;
4. Any other year that can be divided is a leap year.
#! /Bin/sh
Year = $1
If ["$ (Year % 4)"-Ne 0]; then
Echo "This is not a leap year ."
Exit 1
Elif ["$ (Year % 400)"-EQ 0]; then
Echo "this is a leap year ."
Exit 0
Elif ["$ (Year % 100)"-EQ 0]; then
Echo "This is not a leap year ."
Exit 1
Else
Echo "this is a leap year ."
Exit 0
Fi
CTRL + d
//>./Test17.sh 1933
This is not a leap year.
//>./Test17.sh 1936
This is a leap year.

18. convert a single column to multiple columns:

We often format the output of a single row in multiple rows during display. Generally, to complete this operation, we add moreCodeSave the output results to an array or a temporary file, and traverse them again to convert a single row to multiple rows. Here we will introduce a technique for using xargs commands, which can be implemented in a simpler and more efficient way.
/> CAT> test18.sh

#! /Bin/sh
#1. one or more space characters may appear in one line in the passwd file. Therefore, when you directly use the result of the cat command, the For Loop will be cut by space characters, as a result, a line of text is used as an input for multiple for loops. In this way, we have to replace each line of text output by CAT in the SED command globally and replace the space character with % 20. In fact, we can certainly pass the output of CAT/etc/passwd to the cut command in the form of a pipe. The reason for this writing is as follows, the main purpose is to demonstrate how to handle similar problems.
#2. Here, the output of the For Loop is passed to the sort command in the form of a pipe, and the sort command is sorted based on the user.
#3. -xargs-N 2 is the focus of this technique. It combines the sort output. The numeric parameter after the-n option will prompt the xargs command to merge the output into one output, and pass it to the subsequent commands. In this example, xargs merges each two rows obtained from sort into one row, separates them with space characters, and then transmits the merged data to the following awk command. In fact, for awk, you can simply think that xargs reduces the call to it (awk) by half.
#4. If you want to display 3 or more rows in a row, you can change the number after-N to 3 or another higher number. You can also modify the print command in the awk and use the more complex Print Output command to get a more readable output.
For line in 'cat/etc/passwd | SED's // % 20/g''
Do
User = 'echo $ Line | cut-D:-f1'
Echo $ user
Done | \
Sort-K1, 1 | \
Xargs-N 2 | \
Awk '{print $1, $2 }'
CTRL + d
/>./Test18.sh
Abrt Adm
Apache avahi
Avahi-autoipd Bin
Daemon daihw
Dbus FTP
Gameshield
Gopher haldaemon
Halt lp
Mail nobody
NTP Operator
Postfix pulse
Root rtkit
Saslauth Shutdown
Sshd sync
Tcpdump USB muxd
Uucp vcsa

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.