3rd Chapter pipeline character, redirect and environment variable

Source: Internet
Author: User

Chapter Overview:

Don ' t being so excited! Although you have learned hundreds of common Linux commands at this point, as mentioned earlier: "The light command itself does not do a good job ."

The next chapter will learn how to use the shell script, so this chapter should have some link to the role of theoretical knowledge points will be more, but are very practical.

Once the reader has learned the Pipeline command , input and output redirection , wildcard characters , and environment variables , it is possible to combine commands more appropriately and efficiently.

Chapter directory Structure

    • 3.1 Pipe Command character
    • 3.2 Input and output redirection
    • 3.3 Command-line wildcard characters
    • 3.4 Useful Path variables
    • 3.5 Important Environment variables
3.1 Pipe Command character

Pipe command symbol '|' function is to treat the standard output of the previous command as a standard input for the latter command, in the form " command a| Command B". For example, the previous section learned through the grep Text Search command match keyword "/sbin/nologin" to find out all the users who are restricted to the system, if we want to count all the number of users not allowed to log on the system, you can combine the following two commands:

The command to locate the user who is restricted to login is:grep "/sbin/nologin"/etc/passwd

The command to count the number of lines of text is:wc-l

Now to do is to pass the output value of the search command to the statistics command, in fact, as long as the pipe in the middle of the clip can be.

[[email protected] ~]# grep "/sbin/nologin"/etc/passwd | Wc-l33
It's a great feature! We will be presented to the screen of the user information list to " wc-l"The command made further processing, simply too convenient!!

View the files in the/etc directory with page flipping:

[Email protected] ~]# Ls-l/etc/| Moretotal 1400drwxr-xr-x. 3 root root 17:26 abrt-rw-r--r--. 1 root root 17:36 adjtime-rw-r--r--. 1 root root 1518 June 7 Aliases-rw-r--r--. 1 root root 12288 Jul 09:38 aliases.dbdrwxr-xr-x. 2 17:26 alsadrwxr-xr-x, root root. 2 root root 4096 Jul 17:31 alternatives-rw-------. 1 root root 541 Jan anacrontab-rw-r--r--. 1 root root asound.conf-rw-r--r Jan--. 1 root root 1 Jan at.denydrwxr-xr-x. 2 root root 17:27 at-spi2drwxr-x---. 3 root root 17:26 audispdrwxr-x---. 3 root root 17:37 auditdrwxr-xr-x. 4 root root 94 Jul 17:26 Avahi ........ ..... Omit part of the file ...... .....

Send a message to the Linuxprobe User:

[Email protected] ~]# echo "Content" | Mail-s "Subject" Linuxprobe

Switch to Linuxprobe User:

[Email protected] ~]# su-linuxprobexlast login:fri Jul 09:44:07 CST on:0

Check the mail box, and sure enough, there is an e-mail:

[Email protected] ~]$ mailheirloom Mail version 12.5 7/5/10. Type? For help. " /var/spool/mail/linuxprobe ": 1 message 1 new>n 1 root Sun 17:33 18/578" Subject "

Use the non-interactive set user password to change the root password to linuxprobe.

[Email protected] ~]# echo "Linuxprobe" | passwd--stdin rootchanging password for user Root.passwd:all authentication tokens updated successfully.
Of course, students do not misunderstand pipe command can only be used once oh, it can be used: "Command a| Command b| command C”。 In addition, in order to further facilitate the students to remember, understand the pipe character this thing, I will be in the lecture when the pipe symbol is described as "arbitrary door", as a child must have seen Doraemon bar, machine cat often for Nobita and from the pocket to take out a piece of baby, many times on the use of any door this prop, There is a set of Nobita in order to invite friends to play, so with any door across to Mars above, but also put the family's water pipe on Mars, then the pipe symbol is like the data used to cross the arbitrary door, help us improve work efficiency, to complete the unthinkable before the things.

Have a problem? Dare to ask!

Because the reader hardware is different or the operation error may lead to the experimental configuration error, please be patient and carefully look at the operation steps, don't be discouraged ~

Linux Technical Exchange Please add a group: 560843 ( full ), B group: 340829 ( recommended ), click here to see the national group.

* This group features: through password verification to ensure that every group is the "Linux on this Learning" reader, answer more targeted, free of charge to receive customized gifts on a regular basis.

3.2 input and output redirection

To make data processing more efficient with Linux commands, it is particularly necessary to understand the principle of input and output redirection, which is simply described as " using input redirection to import a file into a command, and output redirection is the ability to write information that would otherwise be output to the screen to the specified file ". In the daily work and learning generally use output redirection will be slightly more, so the subdivision with the standard output redirection and error output redirection two different things, after the theory is finished, take a look at the demo:

[[email protected] ~]# ls linuxprobe/[[email protected] ~]# ls xxxxxx/ls:cannot access xxxxxx:no such file or directory

We have just looked at a file named Linuxprobe directory, and then tried to view the file named "xxxxxx" in the directory, showing that the directory does not exist. Although it seems like the command has been executed successfully, there is a difference in the fact that the former executes the standard output and the latter fails to return the error output .

Standard input (STDIN, file descriptor 0): The default is input from the keyboard, and 0 indicates the output from other files or commands.

Standard output (STDOUT, file descriptor 1): The default output to the screen, 1 indicates the file.

Error output (STDERR, file descriptor 2): The default output to the screen, 2 indicates the file.

There are these conditions for input redirection:

Edit
Symbol Role
Commands < Documents Standard input of a file as a command
Commands << Delimiters Read in from standard input until you meet the "delimiter" to stop
Commands < Files 1 > file 2 File 1 as the standard input to the command and output the standard to file 2

There are these conditions for output redirects:

Edit
Symbol Role
Commands > Documents REDIRECT standard output to a file (clears the data from the original file)
Command 2> file REDIRECT error output to a file (clears the data from the original file)
Commands >> Documents REDIRECT standard output to a file (appended to the original content)
Command 2>> file Redirect the error quasi output to a file (appended to the original content)
Commands >> files 2>&1 or commands &> files Write the standard output and error output to the file (appended to the original content)

So let's experiment with several output and input redirects:
Write the help document for the man command to the Readme.txt file:

[[email protected] ~]# man bash > Readme.txt

Write a line of text to the Readme.txt file:

[Email protected] ~]# echo "Welcome to linuxprobe.com" > Readme.txt

Append a line of text to Readme.txt:

[Email protected] ~]# echo "Quality Linux learning materials" >> readme.txt

Because the second time we used the ">" to clear the output redirection, the above man Bash command 's output information in the file will be emptied and then written to the new problem, so now look at the following Readme.txt:

[email protected] ~]# cat readme.txtwelcome to linuxprobe.comquality Linux learning materials

REDIRECT The readme.txt file as input to the wc-l command to calculate the number of rows, which is equivalent to the "cat Readme.txt | Wc-l ".

[Email protected] ~]# Wc-l < README.TXT2

Command with Echo, mail, and pipe characters (|) Send a linuxprobe user an email, but the content can only have a word.

[Email protected] ~]# echo "Content" | Mail-s "Subject" Linuxprobe

If you want to write a letter like email, you can use the input redirection to try it, send a message to the designated mailbox, the title is the Readme, the content is entered by line.
The over is called a section break, which is user-defined and is considered to be the end of the input when the system encounters this delimiter.

[Email protected] ~]# mail-s "Readme" [email protected] << over> I think Linux is very practical> I hope to Learn more> can you teach me?> over the normal case of entering the delimiter will end the input operation and send the message, there will be no error message. [Email protected] ~]#

This time we still use the "ls" command to view the file information, if the file does not exist, the error message output to /root/stderr.txt :

[email protected] ~]# ls linuxprobe 2>/root/stderr.txt-rw-r--r--. 1 root root 0 Mar  1 13:30 linuxprobe

The file is empty and represents the above command without an error:

[Email protected] ~]# Cat/root/stderr.txt

Output the error message for the View xxxxxx Directory command to the/root/stderr.txt file:

[[email protected] ~]# ls xxxxxx 2>/root/stderr.txt

To view the error message for the LS command saved in the Stderr.txt file:

[Email protected] ~]# cat/root/stderr.txtls:cannot access xxxxxx:no such file or directory

Because "linuxprobe" file does exist, all without error message, but "xxxxxx" file is not present, so the error message is output to the specified file.

3.3 command-line wildcard characters

The file name should be the most commonly used parameter object in the daily command, but sometimes it really doesn't remember the full name, so we can search by matching a part of the file name after the wildcard character, for example, to bulk view the hard disk file properties, then the normal command will be:

[[email protected] ~]# ls/dev/sda[[email protected] ~]# ls/dev/sda1[[email protected] ~]# Ls/dev/sda2[[email protected] ~]# Ls/dev/sda3

However, if you do not know the number of partitions or partition number, this time to use the wildcard character, the Bash interpreter supports a variety of text wildcard characters include:

Edit
Wildcard characters Meaning
* Matches 0 or more characters.
? matches any single character.
[0-9] Matches the number within the range.
[ABC] Matches any character that has been out.

To view all device files beginning with SDA:

[Email protected] ~]# ls/dev/sda*/dev/sda/dev/sda1/dev/sda2

View the device files that have a character behind SDA:

[Email protected] ~]# ls/dev/sda?/dev/sda1/dev/sda2

To view the device files that contain 0-9 numbers after SDA:

[Email protected] ~]# ls/dev/sda[0-9]/dev/sda1/dev/sda2

View the device files that are 1 or 3 or 5 behind SDA:

[Email protected] ~]# ls/dev/sda[135]/dev/sda1

In addition, the Bash interpreter supports a number of special character extensions:

Edit
Character Role
\ (back slash) Escaping a single character later
"(single quote) To escape all characters
"" (double quotes) Variable still in effect
"(Anti-quote) Execute Command statement

The value of the variable named price is defined as 5:

[Email protected] ~]# price=5

Want to output "price is 5":

[Email protected] ~]# echo "Price are $PRICE" Price is 5

I want to output "price is $ $", but because the dollar sign conflicts with the $ symbol that represents the variable, the error is:

[Email protected] ~]# echo "Price was $ $PRICE" Price is 3767PRICE

Add a backslash to escape the first $ symbol:

[Email protected] ~]# echo "Price was \$ $PRICE" Price is $

With single quotes, the variable will no longer be evaluated:

[Email protected] ~]# echo ' Price was \$ $PRICE ' Price is \$ $PRICE

After executing uname-a, you can view the version and schema information of the native kernel (the command inside the inverted quotation marks will be executed):

[[email protected] ~]# echo ' uname-a ' Linux linuxprobe.com 3.10.0-123.el7.x86_64 #1 SMP Mon May 5 11:16:57 EDT x86_64 x86_64 x86_64 Gnu/linux
3.4 Useful Path variablesThe alias command is used to set aliases for commands in the format: "Alias alias = Command". For example, if you are concerned about overwriting files when copying files, perform alias cp= "Cp-i"The user is queried for each overwrite.The unalias command is used to suppress the alias of the command in the format: "Unalias alias".

To set the alias for the CP command:

[[email protected] ~]# alias cp= "Cp-i"

To cancel the alias of the CP command:

[Email protected] ~]# Unalias CP
As I said before-everything in Linux is a file, The command file is no exception. That when the user executes a " ls"What happened after the command?" Step one: If the command entered with an absolute/relative path is executed directly (such as executing/bin/ls)。 Step Two: Check whether the alias aliases command. Step three: Judging by bash it is "Internal Command"or"external Command”。
internal command: External command within the Interpreter: command file independent of interpreter
Step four: Command lookup through the path defined in the $path variable.
Ways to view $path variables: echo $PATH
/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
If you want to know if a command is "Internal Command"or"external Command”? Execution Execution " Type command name"The interpreter will tell you yo-$PATH variable is"Interpreter's assistant"It is responsible for telling bash users to execute commands that might be stored there, and then bash will look for them in these directories." In the variable $path, use a colon between the directories " :"You can also customize some of the commands to store directories, such as/root/bin.

To view the contents of the current $path variable:

[Email protected] ~]# echo $PATH/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin

Add a new value to the variable:

[Email protected] ~]# path= $PATH:/root/bin

View the contents of the $path variable at this time:

[Email protected] ~]# echo $PATH/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin
Here's a more classic question: " Why can't I add the current directory (.) in $path That?"Think about it and see the answer ( Answer mode)! answer :Although the $path variable is added to the current directory ( .) In some cases, the user is exempt from the path of the input command, but if the hacker in the more commonly used public directory/tmp stored a trojan file named " ls" or " CD", then the user is very likely to execute the error. Prudent and experienced OPS will be sure to see if there are any suspicious directories in the $path variable before executing the command, after taking over a Linux system. 3.5 Important Environment VariablesWhat I learned from the above $PATHIsn't it practical? There are many important environment variables in the Linux system, we can use Envcommand to view them. Variables are fixed by the " Variable name"Set with user or system" Variable Value"Two-part, if there is a need to directly modify ~
Edit
Variable name Role
HOME User's home directory "Home".
SHELL Which program is the current shell?
Histsize History command record number of bars
MAIL Mail Box File
Lang Language data
RANDOM Random numbers
PS1 Bash prompt
Histfilesize History Command Store Quantity
PATH Locate the executable file in the directory in the path
EDITOR Default text Editor
let's look at the current user's home directory through the variables.

As the root user is currently logged in, it is displayed as/root:

[Email protected] ~]# echo $HOME/root

Switch to Linuxprobe User:

[Email protected] ~]# su-linuxprobelast Login:fri Feb 19:49:57 CST on pts/0

After switching to linuxprobe users, the same "$HOME" variable shows different values:

[Email protected] ~]$ echo $HOME/home/linuxprobe
Suppose you need to set a variable " Workdir", let each user execute the" CD $WORKDIR"All landed in/home/workdirdirectory, how do you do that?
Definition Method: Variable name = new value
View method: Echo $ variable name

Create the directory:

[Email protected] ~]# Mkdir/home/workdir

Set the variables as described earlier:

[Email protected] ~]# Workdir=/home/workdir

Successful switch, great!

[[Email protected] ~]# CD $WORKDIR [[email protected] workdir]# Pwd/home/workdir

Switch to Linuxprobe User:

[email protected] workdir]# su linuxprobelast login:fri Mar 20:52:10 CST on pts/0

So strange, why didn't you switch to the/home/workdir directory:

[Email protected] ~]$ CD $WORKDIR

Use Echo to see that the variable is null:

[Email protected] ~]$ echo $WORKDIR
Now the question is Why an environment variable set by a user cannot be used by another user? The reason is the scope of the variable.The Export command is used to promote a local variable to a global variable in the format: "Export variable name [= Variable value]".

Set the Workdir variable to a global variable:

[Email protected] ~]# export Workdir

Switch to Linuxprobe User:

[email protected] workdir]# su linuxprobelast login:fri Mar 21:52:10 CST on pts/0

It's great. Successfully switched directories:

[Email protected] ~]$ CD $WORKDIR [[email protected] workdir] $pwd/home/workdir

3rd Chapter pipeline character, redirect and environment variable

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.