Look at the 10 Habits of Unix Masters 1th/2 page _unix Linux

Source: Internet
Author: User
Tags mkdir advantage
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 habits. 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.






Back to the top of the page




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 habit. 3 Example: Combining commands with 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 commands with 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: Combining commands with control operators

~ $ cd TMP/A/B/C | | Mkdir-p tmp/a/b/c && tar xvf-c tmp/a/b/c ~/archive.tar







Back to the top of the page




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) variables

~ $ 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
~ $







Back to the top of the page




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 a backslash 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 a backslash for 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.






Back to the top of the page




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 habits. 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: Running 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"







Back to the top of the page




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. Examples of classic usages of the Xargs tool

~ $ 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. Examples of output produced by Xargs tools

~ $ xargs
A

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:

Current 1/2 page 12 Next read the full text

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.