Linux shell Scripts-Basic Learning Notes

Source: Internet
Author: User
Tags line editor

Linux scripting is not too strong, and recently tutorial, after all, Linux shell in the daily work is still very common,

It is more convenient to use, save time and effort.


Here are the study notes, partial theory, followed by a few examples for reference.


Shell Script composition Elements
system commands, Text processing tools (grep\sed, etc.), variables, conditional judgments, looping structures, and functions

--------------------------------------------

Three Musketeers: Grep,sed,awk, and Wc,sort,head, etc.

------------------------------------------------

Echo
Echo-e "\033[40;35m...\033[0m"
Background color: 40-49, 40 black, 41 red, 42 green, 43*** ...
Font Color: 30-39, 30 black, 31 red, 32 green ...

-------------------------------------------------------

Sort
-D Sort by dictionary order
-N Output by number size
-R Reverse Output sort result
-k specifies that the classification is a numeric classification on a field
-t domain delimiter; Split fields with non-whitespace or tab

Sort-k3-n-r-t:/etc/passwd
Sort by a third field, in reverse order of numbers

----------------------------------------------------

Wc:
-C statistics Number of characters
-L count rows
-W statistical number of words

-----------------------------------------

Diff:
To compare files

------------------------------------------------------

Grep:
-N Displays the number of its rows before each line
-V reverse output, print mismatched rows

Ignore case
grep ' [tt]his ' file.txt

Filter out lines not beginning with #
grep ' ^[^#] ' file.txt

Fuzzy matching
grep "S...N" file.txt

----------------------------------------------------

Sed: line Editor
s alternative
I insert before line
Insert after line a
D Delete all rows that match
D Delete first-match rows

Sed-n ' 1,4p '/etc/passwd
-N Prevents printing of the original text, only the modified output is printed
P Printing
1,4 first line to line fourth

Sed '/80/d ' file.txt
Delete rows that first match to 80

Sed ' s/var/usr/g ' file.txt
Replace USR with Var
S is an alternative
g = Replace All
No G is the first match substitution

Sed ' 50,¥s/help/man/g ' file.txt
Instead of the 50 line

---------------------------------------------

awk: Column Editor
-F;
NR Current number of rows processed
Number of columns currently processed by NF
¥0 Select Entire row
¥1 first Column
¥NF last Column

Awk-f: ' {print nr,¥1,¥2} '/etc/password
To: Print out the contents of the first and second columns as separators

Awk-f: ' {print nr,¥1,¥nf} '/etc/password
Print out the first and last columns

-----------------------------------------------------

Scripting specifications
#! /bin/bash
#注释
Body

Script Execution Permissions
chmod u+x hello.sh #u指users, x means execute permission
./hello.sh


Local variables
The variable does not exist in the current shell only under the current user when the user exits the shell
A=1
Echo¥a #如果后面有单位则echo ¥{a}m
1

Environment variables:
Applies to all user processes and fails when the user logs off

Positional variables:
Used to specify the position of the variable

Special variables:
¥# List all parameters passed to the script
¥* (¥@) displays all parameters passed to the script in one character
¥¥ the current process ID number for the script to run
¥? Displays the exit status of the last command. 0 means no errors, other values indicate exceptions

"" can refer to any character or string other than ¥, ', \, character
' is similar to double quotes, but the shell ignores any reference value, shielding its special meaning
' Shell takes the contents of the anti-quote as a system command and executes
\ If the character has a special meaning, the backslash will block its special meaning and prevent misunderstanding

ECHO-E-E is a translator \ n line break

------------------------------------------------

Date +%t Displays the current time of the system
Uptime Display system CPU load

Condition test:
test-option xxx
Returns 0 for true, return 1 for false, return other value result is also false
Xxx

-D Directory
-E is present
-F is a normal file
-s file size equals 0
-r-w-X is readable writable executable

-A and operation
-O or operation
! Non-operational

= = Two strings equal
! = Two Strings Unequal
-Z Empty string
-N Non-empty string

-eq equals
-ne Not equal to
-GT Greater than
-lt less than
-ge greater than or equal to
-le less than or equal to

Condition Selection:
if...else...fi

If condition
Then #条件为真
Command 1
else #条件为假
Command 2
Fi #结束


Case...in ... Esac

Case variable in
Mode 1 command 1.;;
Mode 2 command 2.;;
Esca

* Match any character
? Match any single character
[] Match character Range

---------------------------------------------

Loop structure:

For variable in list
Do
Command 1
Command 2
Done

For i in ' SEQ 1 3 '
Do
SSH hostname-$i
Service httpd Restart
Done

While supports dead loops

While condition
Do
Command 1
Command 2
Done

-------------------------------------------------------------------

function structure
#!/bin/bash
#
Function name ()
{
Command 1
...
}


One-time task scheduling
@ Specify time to schedule one-off tasks

@ [Options] Time
-F read commands or scripts from a file
-m job Complete sending mail
-V Show Execution time
Start the service
Service ATD Start

Delete Task at RM

At-f test.sh 10:00pm Feb 11

Crontab Run scripts regularly
-E adding tasks such as time and script
-L lists the time and script tasks that have been added
-R Delete Current task
-V List Task status

Global/etc/crontab
User/var/spool/cron using-e to add that is under the current user

Crontab User Control
/etc/cron.allow
/etc/cron.deny

* * * * * * Day of the Week

*/5 every five minutes

-------------------------------------------------------------

Example 1:
The date Rose yesterday today
...
20080413 3,384.43 3,294.83-54.37-1.239%
20080621 3,3254.43 3,454.83 59.31 3.231%
...

Listing 20081011 so the data
grep "20081011" Shanghai.txt

List 200806 months of rising data
grep "200806" Shanghai.txt | Grep-v "-"
-V inverse, understood to get non-"-" data

grep "200808" Shanghai.txt |wc-l
Quantitative statistics on August data

Get the most up-to-date data for August
grep "200808" Shanghai.txt | Sort-k5-n | Tail-1
-k5 Sort by Fifth column
-N Sort by number size
-R Reverse Order

Sed-n "$p" to take the last line
Sed-n "1p" take the first line
Head-1 First Line

List the October rally data, with only dates and gains
grep "200810" Shanghai.txt | awk ' {if ($4>0) {print $1,$5}} '
AWK supports shell statements

List data for October gains of 5-80
grep "200810" Shanghai.txt | awk ' {if ($4>5 && $4<80) {print $}} '
Full line

--------------------------------------------------------

Example 2:
Top-n 1 The system load of this second time

#!/bin/bash
#
Cpuidle= ""
Top-n 1 > Sysinfo.txt
Cpuidle= ' cat sysinfo.txt |grep ' Cpu ' |awk ' {print $} ' |awk-f i ' {print '} '
echo "Cpu Idle:${cpuidle}"

Echo 3 >/proc/sys/vm/drop_caches Discard cache, regardless of script

----------------------------------------------------------

Example 3:
Is it possible to ping the 192.168.1.1 and give the results
If ping 192.168.1.1-c 1
Then
echo "192.168.1.1 Online"
Else
echo "192.168.1.1 offline"

----------------------------------------

Example 4:
Writes IP to iplist text
>hoststatus.txt
For IP in ' cat iplist '
Do
If Ping ${ip}-C 1 >/dev/null 2>&1
Then
echo "${ip} online" | Tee-a Hoststatus.txt
Else
echo "${ip} offline" | Tee-a Hoststatus.txt
Done

Sort-t.-k4-n Hoststatus.txt
In. For the split field, sort by the fourth column of numbers

----------------------------------------

Specification:
Try to be less than single quotes '
For special meaning masking for individual special characters, use \
When using single quotation marks for special characters masking, no other reference symbols are used in single quotes
When you execute a shell command using the anti-quote ", you typically add other reference symbols

#在脚本中一般用于描述性注释
; typically used in scripts for exemplary annotations

Variable names are made up of numbers and letters
It is best to use all lowercase English
Try to abbreviate, preferably no more than 6 characters

Scripts are best named in all English lowercase
The version number or date or other use may be used. _-Equal symbols
Try to avoid it? * Space ¥&, etc.
Script naming must not begin with a number
test.1.sh

function specification
Variable names can be made up of numbers and letters
Use the Hump naming method to capitalize the first letter
Multiple word names are supported, but it is best not to exceed two
Try not to abbreviate unless it is well known



































































This article is from the "Heavenly Soul Eternal" blog, please be sure to keep this source http://tianhunyongheng.blog.51cto.com/1446947/1691250

Linux shell Scripts-Basic Learning Notes

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.