[Linux Study Notes] 3rd days: Variable Classification, redirection, pipeline commands, program execution streams, text processing commands, regular expressions, short-circuit Operators

Source: Internet
Author: User
Tags egrep

Variable Classification
Local variable: this variable is only valid locally and invalid for sub-shell. // bin/bash
Environment variable: valid for both local and sub-shell
Export A = 3
Or
A
Export
Export // view the current system environment variable

# Declare-x displaye = "" // specify the number of command lines that can be saved by the output display declare-x histsize = "1000" // Number of command lines that can be saved by history declare-x home =" /root "// the current user's home directory declare-x hostname =" server45.example.com "// the current host name declare-x lang =" zh_cn.gbk "// The language declare-x LOGNAME = "root" // Login User name declare-x oldpwd = "/tmp" // The previous path declare-x Path = "/usr/Kerberos/sbin: /usr/Kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin: /root/bin "declare-x Pwd ="/tmp/scripts "// current path

Printenv // similar to export
Env // display the current environment variable

Special variable: $?
EHCO $? // Whether or not the previous command is successfully executed 0 indicates success 1-failed

[root@server45 ~]# llsss-bash: llsss: command not found[root@server45 ~]# echo $?127

Location Parameter Variable: a variable that can be referenced by a command.
When $1, $2, $3 exceeds 10, it is recommended to add {}$ {11}
Arithmetic Operation:
$ [] // Echo "$ [$ A + $ B]"
$ () // Echo "($ A + $ B ))"

#!/bin/bash#echo "$1+$2 is $[$1+$2]"echo "$1-$2 is $[$1-$2]"echo "$1*$2 is $[$1*$2]"echo "$1/$2 is $[$1/$2]"

Write a script to complete the following functions:
1. pass two integers to the script to calculate and display the sum, difference, product, and quotient of the two integers respectively.

\\// Avoid expanding the variable echo "your salary: \ $1" // This command does not display the value of $1, but shows $1

[root@server45 ~]#  echo "Your Salary : \$1"   Your Salary : $1

Bash command alias
Alias
 

For example, set Cls to Lear for ease of use.
Alias CLS = clear
Unlias CLS
Alias cdnet = 'CD/etc/sysconfig/network' // use ''with spaces'' 
Global variables:/etc/profile,/etc/profild. d/*, and/etc/bashrc apply to all users.

/Etc/bashrc // you can set alias to be valid for all users.
/Etc/profild. d/* // split the profile into slices for ease of Management
/Etc/profild // set the global valid variable, permanently valid
Export dfsf = dfsf // It takes effect only after cancellation
Source/etc/profile // repeat the profile to take effect immediately. It is not recommended
Local variable :~ /. Bash_profile ,~ /. Bashrc ~ /. Bash_logout is only valid for the current user
Profile class:
1. Set Environment Variables
2. Run some commands to be executed during user logon.
Bashrc class
1. Set aliases
2. Set local variables
Bytes -------------------------------------------------------------------------------------------------
Shell classification:
1. Interactive Login Shell
Log on and enter the command
Process:
/Etc/profile -->/etc/profile. d/* --> ~ /. Bash_profile -->/etc/bashrc
2. Non-Logon Shell
During script execution, the system runs automatically and does not need to log on and enter commands.
Process:
~ /. Bashrc -->/etc/profile. d/×

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

Input/Output redirection, MPs queue output stream
I/O redirection is divided:

Standard Input:/dev/stdin, 0, keyboard.
Standard output:/dev/stdout, 1, monitor,> // The command runs normally cat>/tmp/ls1.out
Error output:/dev/stderr, 2, monitor, 2> // command error execution Cat 2>/tmp/ls2.out
// Lessss &>/tmp/ls3.out // &> merge> and 2>

For example

Ls/var>/tmp/var. out 2>/tmp/var. Err // the correct information is var. Out. The error message is in var. Err.

Other redirection
> // Overwrite the output redirection
>>/// Append output redirection
Set-C // enable face avoidance overwrite redirection
Set + C // close
> | // Force Overwrite

Custom output redirection
Exec 3>/tmp/myout. Out // implement multiple redirection to a file to avoid opening or closing a file multiple times and improve script execution efficiency
>>/// Append
<// Read
Ls/var> & 3
Exec 3> &-// close the file

Write a script:
1. Set the value of the variable file to/etc/passwd.
2. read lines 2, 4, 6, 10, 13, and 15 of the file/etc/passwd cyclically and display the content. (Note: line = 'head-2/etc/passwd | tail-1' can get 2nd rows)
3. Save these rows to the/tmp/mypasswd file.

#! /Bin/bash # file =/etc/passwdexec 3>/tmp/mypasswd // open for N in 2 4 6 10 13 15; do line = 'head-$ N $ file | tail-1 'echo $ line> & 1 doneexec 3> &-// close unset file line

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

Pipeline |: sends the output of the first command to the second command for processing.
Echo "123456" | passwd -- stdin rehat // This command will give 123456 to passwd for processing, the -- stdin parameter will make 123456 immediately effective as the user's RedHat Password
Ls/etc | tee/tmp/LS. Out | less // tee can save the output stream to the specified file and hand it to the next command for processing.
The output of multiple commands must be saved to the same file.
Command> A. Out
Command> A. Out

/Dev/nullNull indicates an empty file. Any data put into null is deleted. in Linux, it is a common command that can easily remove the output results, but be careful when using it.

For example: ls/var/TTT &>/dev/null // whatever the result, the output is null and the result is not displayed.
--------------------------------------------------

Program execution flow 

Category:
Sequential execution
Select Branch
Loop execution // this time only learns for Loop
For I in list; do // list is a condition for this loop, also called a list. It can be a character, number, or expression.
Statement1
Statement2
Done

List category:
Simple list: 1 2 3 4
Complex list: This is Tom's cat
Command: 'ls/var'
Wildcard: for I in/var /*


For example:
For line in 'cat/etc/passwd': Dao
Description
Ifs = $ '\ n' // For Loop, except for line breaks

Write a script: add 10 user user1-10

#! /Bin/bash # For I in 1 2 3 4 5 6 7 8 9 10; do // or for I in 'seq 1 10' usradd user $ I echo user $ I | passwd -- stdin user $ I done # seq 1 10 // represents 1 ~ 10 ## you can also use {1 .. 10}

Text processing command cut-D:-d ""

// Specify the separator: Or "-f // specify the nth segment

[root@server45 scripts]# tail -1 /etc/passwd | cut -d: -f6     /home/dean 

Grep and Regular Expression 
 
Grep: Search for regular expressions and print them out.
Grep, egrep, fgrep

Grep [Options] "pattern" file... // grep usage
-I // case insensitive
-V // display the rows that do not match the pattern
-N // display the line number of the matched row in the original text
-An // n rows after display
-BN // display the first n rows
-CN // context, displaying n rows online
-- Color // highlight the matching
Mode
 
Regular Expression, metacharacters re
^ // Specifies the beginning of the line ^ love must be at the beginning of the line
$ // End of the anchor row
. // Match any single character
* // The t before root ** can appear 0 times or any time
?
[] // Match any one of the group of characters
\
\ <// The first Separator
\> // Suffix
X \ (m) \ // X exactly appears m times
X \ (M,) \ // X appears at least m times
X \ (m, n) // X appears at least m times, at most m times
\ (...) \ // Any character of any length

Grep-E = egrep
+ Equivalent to \ {1 ,\}
? Equivalent to \ {0, 1 }\
| Or
'Love | hate' E or H.

Grep exercise

1. display the lines starting with "S" of the/proc/meminfo file with no size difference;
Grep-I s/proc/meninfo // use-I not case sensitive 2. display the rows ending with nologin in/etc/passwd; grep nologin $/etc/passwd // $ indicates the end of the anchor. 3. The/etc/inittab starts with # and is followed by one or more white spaces, followed by any character; grep -- color ^ # [[: sapce:] \ {1,} \/etc/inittab/^ indicates the start of the anchor, [[: Space:]. * used to match multiple consecutive white spaces. 4. The/etc/inittab contains the following rows: (a number between two colons); grep: [0-9]: /etc/inittab 5, display/boot/GRUB/grub. lines starting with one or more white spaces in the conf file; grep ^ [[: Space:] \ {1 ,\}. * "/boot/GRUB/grub. conf grep-e -- color "^ [[: Space:] {1 ,}. * "/boot/GRUB/grub. conf // egrep solution. Note the difference with grep {} 6. display the rows whose names start with a number in the/etc/inittab file and end with the same number as the starting number; grep "^ \ ([0-9] \). * \ 1 "/etc/inittab // use \ (\) \ 1 for frontend and backend matching. Pay attention to" ". * The ifconfig command is used to match any consecutive characters. 7. The ifconfig command can display information related to the IP address of the current host. If you use the grep or other text processing commands to retrieve the IP addresses of the local host, this command does not include 127.0.0.1; ifcofig | grep "Inet ADDR" | grep-V '2017. 0.0.1 '| cut-D: -F2 | cut-d "" F1 // The combination of grep and cut uses 8. The display/etc/sysconfig/network-scripts/ifcfg-eth0 file contains decimal numbers similar to IP address points formatted rows; grep-e "([0-9] {1, 3 }\.) {3 }\. [0-9] {1, 3} "/etc/sysconfig/network-scripts/ifcfg-eth0
Grep "[0-9] \ {1, 3 \}\. "\ {3 \}\. [0-9] \ {1, 3 \}/etc/sysconfig/network-scripts/ifcfg-eth0 // note the difference between egrep and grep

------------------------------------------------------------------------
Short-circuit Operator 
&&// And operation. When you need to determine whether the two commands are used, use the command &: if the first running result is incorrect, continue to run the second command and the result is the second command,

If the first command is correct, the second command will not be running.
1 &&? =?
0 &&? = 0
|// Or operation, use |: if the result of the first command is incorrect, the result is directly the first command,

If the result of the first command is correct, the result is the second command.
1 |? = 1
0 |? =?
 

# Combining the use of/dev/null will play an important role

For example, CAT/tmp/AAA>/tmp BBB | CAT/tmp/AAA &>/dev/null

# If AAA does not exist, the result is directly output to/dev/null without occupying system resources.

 

Write a script:
1. Add 10 users from user1 to user10, but the user must not be added;

#! /Bin/bash # For I in {1 .. 10}; do grep user $ I/etc/passwd &>/dev/null | useradd user $ I // if the user exists, directly output to/dev/null, responsible for adding user $ idoneunset I

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Programming Language:
Script Language: Bash, Perl (linguistics), Python (flexible, concise), Ruby, PHP
It exists as a source program. It does not need to be compiled before execution, but is executed by an interpreter.
Easy to maintain
Poor execution efficiency

Compiled language:
Edit --> compile --> link --> RUN

Script: Command Stack
#! /Bin/bash // standard shebang of the first line
#

Nano myscript. Sh
Chmod + x myscript. Sh
./Myscript. Sh // execute the script

 

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.