Shell programming in Linux

Source: Internet
Author: User
Tags case statement null null

Shell programming

1 echo
-e recognition \ escape character \a \b \ n \ \x hex \ 08 Binary, etc.
#!/bin/bash
Echo-e "Hello World"

Execute script: Mode 1:chmod 755 hello.sh
./hello.sh
Way 2:bash./hello.sh (this way does not need to give execute permission)

1 Historical Orders
You can see the command that has been knocked out by the history direct carriage return. -C empties the cache and the commands in the file-W writes the cache command to the home directory/.bash_history
This command helps the administrator to see what the Linux system has been doing
The/etc/profile file sets the history command. By default, you can save 10,000 articles.
!n means repeating nth command
!! Repeat the previous command
The string repeats the last command that starts with that string

2 Tab key Completion

3 Aliases for commands
Alias alias = ' original command ' Alias Direct return is the query now in the system alias settings

Command execution Order: 1 path Command 2 execute alias 3 internal command to execute bash (such as CD command is not found in Linux executable file, because this command is the command in the shell) 4 environment variable defined in the command

Using the alias defined above, the computer restart will be invalidated, modify the alias to add the VI/ROOT/.BASHRC will be able to modify other users in other users under the. bashrc file

2 common shortcut keys for bash
CTRL + C Ctrl+l ctrl+u (cut all content on the left side of the cursor, or delete a row) ctrl+y (paste) ctrl+d (exit current command) ctrl+r (Search History command)

3 standard input and output
Keypad/dev/stdin 0 Standard input
Display/dev/sdtout 1 standard output
Display/dev/sdtout 2 standard error output

Output redirection: Commands > Files are overwritten to output the correct input of the command to the specified file or device
Commands >> files are appended to the correct input output of the command to the specified file or device
Error command 2> file to overwrite the error output of the command to the specified file or device
Error command 2>> file to append the error output of the command to the specified file or device

Actual Work use: command &> file to overwrite the correct or incorrect input of the command to the specified file or device
Commands &>> files are appended to the correct or incorrect input output of the command to the specified file or device
Commands >> files 1 2>> file 2 Save the correct command to file 1 save the wrong command to file 2

Command &>/dev/null null file is a "garbage bin"
Enter redirection:
WC [option-C Statistics bytes-W Statistics number of words-l count rows] < [filename]
WC return input ctrl+d end WC command
WC < file name


4 multiple command execution
; command 1; Command 2 Multiple command order execution, no logical connection between commands
&& command 1&& command 2 logic and command 1 Execute command 2 correctly
| | command 1| | Command 2 logic or command 1 correct execution of command 2 does not execute, in contrast to execute

Example: Date;dd if=/dev/zero of=/root/testfile bs=lk count=10000;date
Command && echo Yes | | Echo no
5 pipe break
Command 1 | command 2
Command 1 The correct execution of output as command 2 Action object
Ll-a/etc | more
Netstat-an | grep established
TOO
6 wildcard character
? (one)
* (0 or more)
[ABC] matches any character in brackets
[A-z] matches any one of the characters in the range in parentheses
[^0-9] matches any character except the 0-9 range
7 special symbol
' In single quotes, all special symbols have no special meaning
"" in double quotes $ ' \ has special meaning to call variable value, reference command, escape character
' is generally a command,
generally do not use anti-quotes, & (command) instead of anti-quote
#注释
$ to invoke the value of a variable
\ Escape character cancels the special function of a special symbol
\ n \ \ \ is a whole symbol and cannot be used as an escape character

8 user-defined variable
variable not allowed to start with a number
in bash, The default type of a variable is a string, and if you want to perform a numeric operation, you must specify the variable type as numeric. The

variable is concatenated with an equal sign, there must be no space on either side of the equal sign
variable value if there is a space, you need to enclose it in single or double quotation marks

variables are: User-defined variables, environment variables, positional parameter variables, predefined variable

variable overlays:
a=000
a=$ (a) 123
A= "$a": 123

Set command to view all current variables.
Cancel variable: unset variable name
9 environment variable
User-defined variable only takes effect in the current shell.

The environment variables defined by the command will take effect in the current shell and all child shells of the shell, equivalent to global variables, and if the environment is written to the appropriate configuration file, the environment variable will take effect in all shells.

Parent and child bash queries through the Pstree command

setting of environment variables;
Export variable name = variable name (equivalent to defining a global variable)
For existing user-defined variables, use directly: The export variable name defines the variable as a current environment variable
ENV query variable
unset Deleting a variable

Common system-level environment variables:
PATH
Path= "$PATH":/tmp/hello.sh
With this definition, hello.sh can be executed directly, but this is a temporary effect.

PS1 defining a system Prompt variable can modify the format of the prompt

10 Position parameter variable
$n N is a number, and $ A represents the command itself, $1-$9 represents the first to the Nineth parameter, and more than 10 of the parameters need to be enclosed in curly braces, $ (10).
Use the method to refer to the video bar, not good to write, not happy to write.
$* this variable represents all parameters and all parameters as a whole
[email protected] with #*, representing all parameters, but #@ to distinguish the parameters
$# Number of parameters

11 Pre-defined variables
$? The return state of the last command executed, if 0, indicates that the previous command was executed correctly, and that the previous command did not execute correctly if nonzero
$$ process Number (PID) of the current process
Add & at the end of the command, indicating that the program is put into the background
$! Process number (PID) of the last process running in the background

Bash variables-numeric operations and operators
Numeric operations:
Method One:
Declare [+/-][option] Variable name
-Set type properties for variables
+ Cancel the Type property of a variable
-I declares a variable as an integer
-X declares a variable as an environment variable as with the Export command
-P Displays the declared type of the specified variable
Method Two:
Expr and let numeric arithmetic tools (not commonly used)
Method Three:
$ ((expression)) or $[(Op-op)

Operator:
Basic Full support

13 variable test and content substitution

14 Introduction to the environment variable configuration file
Source Configuration file
Or. Configuration file
The above command can omit to modify the configuration file after you must re-login this step

The environment variable configuration file is primarily defined as a system default environment variable that takes effect on the system's operating system, such as Path
Path= "$PATH":/root This form of modify environment variable is only valid for the current

The configuration file of the corresponding environment variable mainly includes:/etc/profile (valid for all users)
/etc/profile.d/*.sh (this represents a set of environment variable profiles that are valid for all users)
~/.bash_profile (valid for yourself, to. Start with hidden files)
~/.bash_profile (valid for himself)
/ETC/BASHRC (valid for all users)

15 Other environment variable configuration files
~/.bash_logout environment variable configuration file in effect when logging off
~/bash_history History command to save the configuration file (log off before writing or use history-w)
/etc/issue Local Terminal login information (no use for remote login)
/etc/issue.net Remote Login information (local escape character not available) This needs to be set in/etc/ssh/sshd_config
/ETC/MOTD is valid both remotely and locally, but for login information after landing

16 Basic Regular Expressions
Regularization is the grep awk sed used to match the string
Wildcard is used to match the file name of *? The LS find CP does not support regular expressions, so it can only be matched using the shell's own wildcard character.

The wildcard is the full end match, which means that the LS AA list only AA will not be listed AABB
A regular is a string that contains a match that is a line in a file that lists this line

Regular:
* The previous character matches 0 or more times, note is the previous character, different from the wildcard character, "A *" does not have any meaning "aa*" This is the line that matches the first letter a string
(The wildcard character * denotes any number of characters?) Represents a character)

. Matches any one character except the line break (equivalent to a wildcard?). ) (. * This is the equivalent of the wildcard character *)

^ Match beginning of Line
$ Match Line End (^$ so write matches blank line) grep-n "^$" file
[] matches any one of the characters specified in the brackets, matching only one character
[^] matches any character except the brackets
\ escape Character
\{n\} indicates that the preceding character appears exactly n times [0-9]\{4\}
\{n,\} indicates that the preceding character appears not less than n times
\{n,m\} indicates that the preceding characters appear at least n times
17 Character Processing commands
Cut Field Extraction command
Cut [options] filename-F lift the column (the default tab is the most delimiter, if it is not the TAB key, you need to specify what the delimiter is)-D to cut the column by the specified separator
When the delimiter is a space, you need to use the awk command
printf Command Format Print command
%m.nf m represents the width of floating-point data, and N represents the number of decimal digits
%i Integer
%s string
printf '%s\n ' 1,2,3,4 printf '%s%s%s\n ' 1 2 3 4 5 6 This would be considered to have two sets of strings

The reason for learning printf is that the awk command cannot invoke system commands and can only output content using the printf command

Enter in Linux is \ r \ nand Windows is \ r \ n
the awk command is more complex see video bar The default identifier is a space and tab
Awk ' condition {action} condition {action} ' file
Df-h | awk ' {printf $ \ t "$ $" \ n "} '

awk ' BEGIN {printf" This is a transcript\n "}{printf" \ n "} ' file
where BEGIN means printing a This is a trans before formal printing Cript, cancel out awk default read the first line with a space or tab delimiter
awk ' BEGIN {fs= ":"}end{printf this is END}{printf "\ n"} ' file specifies the delimiter:
awk ' $6>1 0{printf hahaha} '

sed command Lightweight Flow editor SED is primarily used to select, replace, delete, and add new
sed [options] ' [action] ' File name
option
-n The general SED command will output all data to the screen, and if you add this option, only the rows processed by the SED command will be output to the screen
-e allows multiple sed command edits to the input data
-I directly modify the file to read the data with the result of the SED modification, instead of the screen output
Action
a\ append
c\ line substitution
i\ Insert
D delete
P print
s string replace

Sed ' 2a hello ' file means after the second line append Hello
Sed ' 2i hello ' file means to insert Hello before the second line
Sed ' s/old string/new string/g ' file sed ' 4/hello/wdx/g ' file name on line 4th of the Hello string changed to WDX string
Sed-e ' s/hello/edx/g;s/world/cyj/g ' file name replaces all of the Hello files with edx, replacing world with Cyj


Sort command sort [options] file name
-F ignores case
-N Sorts by numeric type, by default using string type sorting
-R Reverse Sort
-t Specifies the delimiter, the default delimiter is a tab
-K n[,m] Sort by the specified field range, ending with the first n field M field
WC Statistics Command
-L Statistic Line
-W statistical number of words
-M statistic character number

Test condition judgment
-B file, determine if the file exists, and whether it is a block device file (is a block device file is true)
-d file to determine if the file exists and whether it is a directory file (the directory is true)
-e file to determine if the file exists
-F file to determine if the file exists and whether the file is a normal file
-r file to determine if the file exists and to determine if there is Read permission
-W file, determine if the file exists, write
-x file, which determines whether the file exists, executes
Files 1-nt File 2 Determine if the modification time of file 1 is newer than file 2
Files 1-ot File 2 Determine if the modification time of file 1 is greater than the old file 2
Files 1-ef file 2 Determine whether the file 1 is the same as the inode number of file 2, which can be understood as whether it is the same file (hard link)

There are also commands for judging integers and strings
-eq judgment equality for integers
= = Determines whether strings are equal
Judge 1-a judgment 2 logic and
Judge 1-o Judge 2 logic or
The judgment logic does not reverse the original judgment.

Test [options] File
or [Options file]

The IF statement
If Judgment (Test statement)
Then
Statement
Else
Statement
Fi

If judgment
Then
Statement
Elif judgment
Then


Back up the MySQL database
#!/bin/bash
Ntpdate Asia.pool.ntp.org$>/dev/null
date=$ (date +%y%m%d) #当前系统时间
size=$ (Du-sh/var/lib/mysql) #统计数据库的大小, assigning size to a variable
。。。。。。。。。。 Watch the video or PPT.

Case statement
Case $ variable name in
"Value 1")
If the value of the variable equals the value 1, execute the program 1
;;
*)
are not performing the program segment

Esac

For loops
For variable in value 1 value 2 value 3
Do
Program Segment
Done

ls > Ls.log
For variable in $ (cat ls.log)
Do
Program Segment
Done

TAR-ZXF Unpacking
TAR-ZTF Pressure Pack

Another for language
S=0
For ((i=1;i<=100;1=i+1))
Do
s=$ ((s+i))
Done
echo "The sum of 1+2+.....+100 is": $s

Bulk Add Users


The while loop and the until loop
While loop is an indefinite loop, also known as a conditional loop, as long as the conditional judgment is established, the loop will continue until the conditional judgment is not established, the loop will not stop, which is not the same as for the fixed loop.

I=0
S=0
While [$i-le] #小于等于
Do
s=$ (($s + $i))
i=$ (($i + 1))
Done
echo "The sum is: $s"

The Until loop and the while loop are reversed, and the until loop is looped as long as the conditional judgment is not established, and the loop is executed, and once the loop condition is established, it does not loop

I=1
S=0
Until [$i-GT] #大于
Do
s=$ (($s + $i))
i=$ (($i + 1))
Done
echo "The sum is: $s"


What the scripting language sees is that it does not need to be "compiled" and executed, but side-compiled.


Since Windows and Linux have different carriage returns, the conversion from Windows to Linux executes: Dos2unix file name

Shell programming in Linux

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.