10 good habits of Linux operation __linux

Source: Internet
Author: User
Tags mkdir posix

Java EE Development of various types of resources download list, the history of the most complete IT resources, personal collection summary.

This is a good habit to follow in the 10 Linux system command line operation mode, they can not only make your operation faster, but also reduce the likelihood of your mistakes. Each of them is


1. Set up a complete directory tree with a mkdir statement
Example:
$ mkdir-p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}


2. When decompressing, use the-C option to specify the target folder
Example:
$ tar xvf-c tmp/a/b/c newarc.tar.gz


3. Use logical controls to combine your actions
Example:
$ cd tmp/a/b/c && tar xvf ~/archive.tar


4. Use double quotes to prevent the system from being misunderstood.
Example:
$ ls tmp/
A b
$ var= "tmp/*"
$ echo $VAR
tmp/a tmp/b
$ echo "$VAR"
tmp/*


5. Use ESC character to enter the long instruction branch
Example:
$ cd TMP/A/B/C | | /
> Mkdir-p tmp/a/b/c &&/
> Tar xvf-c tmp/a/b/c ~/archive.tar


6. Combine your actions into a single list
Example:
$ (cd tmp/a/b/c/| | mkdir-p tmp/a/b/c &&/
> var= $PWD; CD ~; Tar xvf-c $VAR Archive.tar)/
> | Mailx admin-s "Archive contents"


7. Use the Xargs command to filter the output of the Find command.
Example:
~/tmp $ ls-1 | Xargs
December_report.pdf README a Archive.tar mkdirhier.sh
~/tmp $ ls-1 | Xargs file
December_Report.pdf:PDF Document, version 1.3
Readme:ascii text
A:directory
Archive.tar:POSIX Tar Archive
Mkdirhier.sh:Bourne Shell Script Text executable
~/tmp $


8. Know when to use the grep count and when not to
Example:
~ $ time grep and Tmp/a/longfile.txt | Wc-l
2811

Real 0m0.097s
User 0m0.006s
SYS 0m0.032s


9. Use awk instead of grep when you want to determine whether a particular domain is eligible
Example:
~/tmp $ ls-l | awk ' $-= ' Dec '
-rw-r--r--3 Joe Joe 5096 Dec 14:26 Archive.tar
-rw-r--r--1 root 238 Dec 08:19 README


10. Do not list the contents of the file with the Cat command and pass it to Grep,grep to find the file directly
Example:
~ $ time grep and Tmp/a/longfile.txt
2811

Real 0m0.010s
User 0m0.006s
SYS 0m0.004s

Reprint statement: This article turns from http://jandan.net/2006/12/17/learn-10-good-unix-usage-habits.html

============================================================================

Extended Reference:

10 Habits of a UNIX master

Introduction
When you use a system frequently, you tend to get stuck in some sort of fixed usage pattern. Sometimes, you don't get into the habit of doing things in the best way possible. Sometimes, your bad habits can even lead to confusion. One of the best ways to correct such shortcomings is to consciously adopt a good habit of resisting these bad habits. This article presents 10 UNIX command-line habits that are worth taking--a good habit to help you overcome many common usage quirks and improve command-line productivity in the process. These 10 good habits are listed below, followed by a more detailed description.

use 10 good habits
The ten good habits to adopt are:
Create a directory tree in a single command.
Change the path, and do not move the archive.
Use the command and control operators in combination.
Reference variables carefully.
Use an escape sequence to manage longer input.
Groups the commands in the list.
Use Xargs outside of find.
Learn when grep should perform the count-when it should be bypassed.
Matches some of the fields in the output, not just the rows.
Stop using the pipe for cat.

Creating a directory tree in a single command

Listing 1 illustrates one of the most common UNIX bad habits: Defining a directory tree at a time.

Listing 1. Bad habits. 1 Example: Individually define each directory tree
~ $ mkdir tmp
~ $ CD tmp
~/tmp $ mkdir A
~/tmp $ CD A
~/TMP/A $ mkdir B
~/TMP/A $ cd B
~/tmp/a/b/$ mkdir C
~/tmp/a/b/$ cd C
~/TMP/A/B/C $

It is much easier to use the mkdir-P option and to create all the parent directories and their subdirectories in a single command. But even for administrators who know this option, they are still bound to progressively create each level of subdirectories when they create subdirectories on the command line. It is worthwhile to take the time to consciously develop this good habit:

Listing 2. Good habit. 1 Example: Use a command to define a directory tree ~ $ mkdir-p tmp/a/b/c

You can use this option to create an entire complex directory tree (which is ideal for use in scripts), rather than just creating a simple hierarchy. For example:

Listing 3. Good habit. Another example of 1: Using a command to define a complex directory tree ~ $ mkdir-p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

In the past, the only excuse for defining a directory individually is that your mkdir implementation does not support this option, but it is no longer the case on most systems. IBM, aix®, mkdir, GNU mkdir, and other systems that comply with the Single UNIX specification (the one UNIX specification) now have this option.

For a few systems that still lack this functionality, you can use the Mkdirhier script (see Resources), which is the wrapper for the mkdir that performs the same function: ~ $ mkdirhier project/{lib/ext,bin,src,doc/{html, INFO,PDF},DEMO/STAT/A}

change path; do not move archive

Another bad usage pattern is to move the. Tar archive file to a directory that happens to be the directory where you want to extract the. tar file. You don't really need to do that. You can extract any. tar archive file to any directory at your whim--this is the purpose of the-C option. When you extract an archive file, use the-C option to specify the directory in which to extract the file:

Listing 4. Good habits. 2 Example: Use option-C to decompress. Tar Archive file ~ $ tar xvf-c tmp/a/b/c newarc.tar.gz

Rather than moving an archive file to the location where you want to extract it, switch to that directory, and then unzip it, it is preferable to develop the habit of using-c-especially when the archive file is located somewhere else.

Combining commands with control operators

You may already know that in most shells, you can place a semicolon between commands on a single command line (;) To assemble the commands. The semicolon is the Shell control operator, although it is useful for concatenating discrete commands on a single command line, but it does not apply in all cases. For example, suppose you use semicolons to combine two commands, where the proper execution of the second command depends entirely on the successful completion of the first command. If the first command does not exit as you expect, the second command will still run-the result will be a failure. Instead, you should use a more appropriate control operator (this article describes some of these operators). As long as your Shell supports them, it's worth the habit of using them.

Run a command only if another command returns a 0 exit state

Use the && control operator to combine two commands to run the second command only if the first command returns 0 exit states. In other words, if the first command runs successfully, the second command will run. If the first command fails, the second command does not run at all. For example:

Listing 5. Good habits 3 Example: combining command and Control operators ~ $ cd tmp/a/b/c && tar xvf ~/archive.tar

In this case, the archived content is extracted into the ~/TMP/A/B/C directory, unless the directory does not exist. If the directory does not exist, the tar command does not run, so no content is extracted.

Run a command only if another command returns a non-0 exit state

Similarly, | | The control operator separates two commands and runs the second command only if the first command returns a non-0 exit state. In other words, if the first command succeeds, the second command does not run. If the first command fails, the second command runs. This operator is typically used when testing for the existence of a given directory, and if the directory does not exist, it is created:

Listing 6. Good habit. Another example of 3: Combining command and Control operators ~ $ cd TMP/A/B/C | | Mkdir-p tmp/a/b/c

You can also use the control operators described in this section in combination. Each operator affects the last command run:

Listing 7. Good habits. 3 Combination Example: Use the command and control operators together ~ $ cd TMP/A/B/C | | Mkdir-p tmp/a/b/c && tar xvf-c tmp/a/b/c ~/archive.tar

Carefully referencing variables

Always be cautious about using Shell extensions and variable names. It is generally best to include variable calls in double quotes unless you have sufficient reason not to do so. Similarly, if you use the variable name directly after the alphanumeric text, you also make sure that the variable name is included in the brackets ([]) to differentiate it from the surrounding text. Otherwise, the Shell interprets the trailing text as part of the variable name--and most likely returns a null value. Listing 8 provides examples of various references and references to variables and their effects.

Listing 8. Good Habits 4 Example: reference (and unreferenced) variable ~ $ ls tmp/
A b
~ $ var= "tmp/*"
~ $ echo $VAR
tmp/a tmp/b
~ $ echo "$VAR"
tmp/*
~ $ echo $VARa

~ $ echo "$VARa"

~ $ echo "${var}a"
Tmp/*a
~ $ echo ${var}a
tmp/a
~ $

Use escape sequences to manage longer input

You may have seen a code example that uses a backslash (/) to extend a longer line to the next line, and you know that most shells treat as a single long line what you type on subsequent lines of a backslash join. However, you may not be able to take advantage of this feature in the command line as usual. Backslashes are especially useful if your terminal does not handle multiple-line wrapping correctly, or if your command line is smaller than usual (for example, when there is a long way to go under a prompt). Backslashes are also useful for understanding the meaning of long input rows that you type, as shown in the following example:

Listing 9. Good habit. 5 Example: Use backslashes for long input ~ $ cd TMP/A/B/C | | /
> Mkdir-p tmp/a/b/c &&/
> Tar xvf-c tmp/a/b/c ~/archive.tar

Alternatively, you can use the following configuration:

Listing 10. Good habit 5 Alternative example: Use the backslash for the long input ~ $ cd TMP/A/B/C/
> | | /
> Mkdir-p tmp/a/b/c/
> &&/
> Tar xvf-c tmp/a/b/c ~/archive.tar

However, when you divide an input row into multiple lines, the Shell always treats it as a single contiguous row, because it always deletes all backslashes and extra spaces.

Note: In most shells, when you press the UP ARROW key, the entire multiline input is redrawn onto a single long input line.

Group commands in the list

Most shells have a way to group commands in a list so that you can pass their aggregate output down to a pipe, or redirect any part or all of its streams to the same place. You can generally do this by running a list of commands in a subshell or by running a list of commands in the current Shell.

Running a list of commands in Subshell

Use parentheses to include a list of commands in a single group. Doing so will run the command in a new Subshell and allow you to redirect or collect the output of the entire set of commands, as shown in the following example:

Listing 11. Good habit. 6 Example: Run a list of commands in Subshell ~ $ (cd tmp/a/b/c/| | mkdir-p tmp/a/b/c &&/
> var= $PWD; CD ~; Tar xvf-c $VAR Archive.tar)/
> | Mailx admin-s "Archive contents"

In this example, the contents of the archive are extracted to the tmp/a/b/c/directory, and the output of the grouped commands, including the list of extracted files, is sent through mail to address admin.

Using Subshell is preferable when you redefine environment variables in the list of commands, and you do not want those definitions to be applied to the current Shell.

Run a list of commands in the current Shell

Enclose the list of commands in braces ({}) to run in the current Shell. Make sure that you include spaces between the parentheses and the actual commands, or the Shell may not interpret the parentheses correctly. Also, make sure that the last command in the list ends with a semicolon, as shown in the following example:

Listing 12. Good habit. Another example of 6: Run a list of commands in the current Shell ~ $ {cp ${var}a. && chown-r guest.guest a &&/
> Tar cvf newarchive.tar A; } | MAILX admin-s "New Archive"

Use Xargs outside of find

Use the Xargs tool as a filter to take full advantage of the output selected from the Find command. Find runs usually provides a list of files that match certain criteria. This list is passed to Xargs, which then uses the file list as a parameter to run some other useful commands, as shown in the following example:

Listing 13. Xargs Tool Classic Usage Example ~ $ find Some-file-criteria Some-file-path | /
> Xargs some-great-command-that-needs-filename-arguments

However, do not view Xargs only as an auxiliary tool for find; it is one of the underutilized tools, and when you develop the habit of using it, you will want to do all the experiments, including the following usage.

Pass a space-delimited list

In the simplest invocation form, Xargs is like a filter that accepts a list (each member on a separate line) as input. The tool places those members on a single white-space-delimited line:

Listing 14. Sample output from Xargs tool ~ $ xargs
A
B
C
Control-d
A b C
~ $

You can send the output of any tool that uses Xargs to output file names to get a list of parameters for other tools that accept file names as arguments, as shown in the following example:

Listing 15. Example of the use of the Xargs tool ~/tmp $ ls-1 | Xargs
December_report.pdf README a Archive.tar mkdirhier.sh
~/tmp $ ls-1 | Xargs file
December_Report.pdf:PDF Document, version 1.3
Readme:ascii text
A:directory
Archive.tar:POSIX Tar Archive
Mkdirhier.sh:Bourne Shell Script Text executable
~/tmp $

The Xargs command is not just for passing file names. You can also use it any time you want to filter the text to a single row:

Listing 16. Good habits. 7 Example: Use the Xargs tool to filter text to a single row ~/tmp $ ls-l | Xargs
-rw-r--r--7 Joe Joe 12043 20:36 december_report.pdf-rw-r--r--1/
Root root 238 Dec 08:19 README drwxr-xr-x Joe Joe 354082 Nov 02/
16:07 a-rw-r--r--3 Joe Joe 5096 Dec 14:26 archive.tar-rwxr-xr-x 1/
Joe Joe 3239 Sep 12:40 mkdirhier.sh
~/tmp $

Use Xargs carefully

Technically speaking, using Xargs is rarely a problem. By default, the file end string is an underscore (_), and if the character is sent as a single input parameter, all the content after it is ignored. To prevent this, you can use the-e flag, which completely disables the end string without parameters.

Learn when grep should perform a count--when you should bypass

Avoid sending grep to wc-l by piping to count the number of output rows. The grep-C option provides a count of the rows that match a particular pattern and is generally faster than sending to the WC through a pipe, as shown in the following example:

Listing 17. Good habits. 8 Example: Row count with and without grep ~ $ time grep and Tmp/a/longfile.txt | Wc-l
2811

Real 0m0.097s
User 0m0.006s
SYS 0m0.032s
~ $ time Grep-c and Tmp/a/longfile.txt
2811

Real 0m0.013s
User 0m0.006s
SYS 0m0.005s
~ $

In addition to the speed factor, the-C option is also a good way to perform counting. For multiple files, grep with the-C option returns a separate count of each file, one count per line, while a pipe for WC provides a combined total of all files.

However, regardless of speed, this example shows another common error to avoid. These counting methods provide only the number of rows that contain matching patterns--if that's the result you're looking for, that's fine. However, in the case of multiple instances of a particular pattern in a row, these methods cannot give you a true count of the actual number of matching instances. In the final analysis, to count the instances, you still need to use WC to count. First, run the grep command using the-o option (if your version supports it). This option outputs only the matching pattern, one pattern per line, and not the line itself. However, you cannot use it in conjunction with the-C option, so you use Wc-l to count the rows, as shown in the following example:

Listing 18. Good habits. 8 Example: using grep to count pattern instances ~ $ grep-o and Tmp/a/longfile.txt | Wc-l
3402
~ $

In this case, the call to WC is a bit faster than the second call to grep and the insertion of a virtual mode (such as grep-c) to match and count the rows.

Match some of the fields in the output, not just the rows

Tools such as awk are superior to grep when you want to match only the patterns in a particular field in the output row.

The following simplified example shows how to list only the files that were modified in December.

Listing 19. Bad habits. 9 Example: use grep to find patterns in a specific field ~/tmp $ ls-l/tmp/a/b/c | grep Dec
-rw-r--r--7 Joe Joe 12043 20:36 December_report.pdf
-rw-r--r--1 root 238 Dec 08:19 README
-rw-r--r--3 Joe Joe 5096 Dec 14:26 Archive.tar
~/tmp $

In this example, grep filters the rows and prints all the files with Dec in their modified date and name. Therefore, files such as december_report.pdf are matched, even though it has not been modified since January. This may not be the result you want. In order to match patterns in a particular field, it is best to use awk, where one of the relational operators matches the exact field, as shown in the following example:

Listing 20. Good Habits 9 Example: use awk to find patterns in a specific field ~/tmp $ ls-l | awk ' $-= ' Dec '
-rw-r--r--3 Joe Joe 5096 Dec 14:26 Archive.tar
-rw-r--r--1 root 238 Dec 08:19 README
~/tmp $

For more detailed information on how to use awk, see Resources.

Stop using a pipe to cat

A common basic usage error with grep is to send the output of cat to grep to search for the contents of a single file through a pipe. This is absolutely unnecessary and is simply a waste of time, because tools such as grep accept filenames as arguments. You do not need to use cat in this case, as shown in the following example:

Listing 21. Good habits and bad habits. 10 Example: using grep with and without cat
~ $ time Cat Tmp/a/longfile.txt | grep and
2811

Real 0m0.015s
User 0m0.003s
SYS 0m0.013s
~ $ time grep and Tmp/a/longfile.txt
2811

Real 0m0.010s
User 0m0.006s
SYS 0m0.004s
~ $

This error exists in many tools. Because most tools accept standard input with a hyphen (-) as a parameter, the parameters are usually not valid even if you use cat to disperse multiple files in stdin. It is really necessary to perform a connection first before the pipeline only if you are using cat with one of multiple filtering options.

Concluding remarks: Forming good habits

It's a good idea to check any bad usage patterns in your command-line habits. Poor usage patterns can slow you down and usually cause unexpected errors. This article describes 10 new habits that can help you get rid of many of the most common usage errors. Developing these good habits is a positive step in strengthening your UNIX command line skills.

Reprint statement:This paper turns from http://hi.baidu.com/zkheartboy/blog/item/fa1797cb65ff71fd52664f96.html

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.