Introduction
When you often use a system, it is often in a fixed usage mode. Sometimes, you do not get into the habit of doing things in the best way possible. Sometimes, your bad habits may even lead to confusion. One of the best ways to correct such defects is to consciously adopt the good habits of resisting these bad habits. This article presents 10 Unix Command Line habits worth using-a good habit of helping you overcome many common usage quirks and improve the efficiency of command line work in this process. These 10 good habits are listed below, and a more detailed description is given later.
Use 10 good habits
Ten good habits to use are:
Create a directory tree in a single command.
Change the path. Do not move the archive.
Combines commands with control operators.
Exercise caution when referencing variables.
Use escape sequences to manage long input.
Group commands in the list.
Use xargs outside of find.
Know when grep should execute count-When should bypass.
Matches some fields in the output, not just the rows.
Stop using pipelines for Cat.
Create a directory tree in a single command
Listing 1 demonstrates one of the most common UNIX bad habits: defining a directory tree at a time.
Listing 1. Bad habits 1 Example: define each directory tree separately
~ $ Mkdir TMP
~ $ CD TMP
~ /Tmp $ mkdir
~ /Tmp $ CD
~ /Tmp/A $ mkdir B
~ /Tmp/A $ CD B
~ /Tmp/a/B/$ mkdir C
~ /Tmp/a/B/$ CD C
~ /Tmp/A/B/C $
Using the-P option of mkdir and creating all parent directories and Their subdirectories in a single command is much easier. However, even for administrators who know this option, they are still bound to gradually creating sub-directories at each level when creating sub-directories on the command line. It is worth taking the time to consciously develop this good habit:
Listing 2. Example of Good Habit 1: Use a command to define a directory tree
~ $ Mkdir-P tmp/A/B/C
You can use this option to create the entire complex directory tree (which is ideal for use in scripts), instead of simply creating a simple hierarchy. For example:
Listing 3. Another example of good habit 1: using a command to define a complex directory tree
~ $ Mkdir-P project/{lib/EXT, bin, SRC, DOC/{HTML, info, PDF}, demo/STAT/}
In the past, the only excuse for defining directories separately was that your mkdir implementation did not support this option, but it was no longer the case in most systems. This option is now available for IBM, Aix, mkdir, GNU mkdir, and other systems that comply with a single UNIX specification.
For a few systems that still lack this function, you can use the mkdirhier script (see references), which is the packaging of mkdir that executes the same function:
~ $ Mkdirhier Project/{lib/EXT, bin, SRC, DOC/{HTML, info, PDF}, demo/STAT/}
Change path; Do not move the archive
Another bad usage mode is to move the. tar archive file to a directory, because this directory is exactly the directory where you want to extract the. tar file. In fact, you do not need to do this. You can decompress any. tar archive file to any directory-this is the purpose of the-C option. When extracting an archive file, use the-C option to specify the directory in which the file is to be decompressed:
Listing 4. Example of Good Habit 2: Use Option-C to decompress the. tar archive file
~ $ Tar xvf-C tmp/A/B/C newarc.tar.gz
In contrast to moving an archive file to the location where you want to decompress it, switch to this directory before decompressing it, the habit of using-C is more desirable-especially when the archive file is located somewhere else.
Back to Top
Combine commands with Control Operators
You may already know that in most shells, you can combine commands on a single command line by placing a semicolon (;) between commands. This Semicolon is a shell control operator. Although it is useful for concatenating discrete commands on a single command line, it is not applicable to all situations. For example, if you use a semicolon to combine two commands, the correct execution of the second command is completely dependent on the successful completion of the first command. If the first command does not exit as expected, the second command will still run -- the result will cause failure. Instead, you should use more appropriate control operators (some operators described in this article ). As long as your shell supports them, it is worth developing the habit of using them.
Run a command only when the other command returns the zero exit status.
Use the & control operator to combine two commands to run the second command only when the first command returns the zero exit status. In other words, if the first command runs successfully, the second command runs. If the first command fails, the second command does not run at all. For example:
Listing 5. Examples of good habits 3: combining commands with Control Operators
~ $ CD tmp/A/B/C & tar xvf ~ /Archive.tar
In this example, the archived content is extracted ~ /Tmp/A/B/C directory, unless the directory does not exist. If the directory does not exist, the tar command will not run, so it will not extract any content.
A command is run only when another command returns a non-zero exit status.
Similarly, | the control operator separates two commands and runs the second command only when the first command returns a non-zero exit status. In other words, if the first command is successful, the second command will not run. If the first command fails, the second command will run. This operator is usually used to test whether a given directory exists. If the directory does not exist, create it:
Listing 6. Another example of good habits 3: combining commands with Control Operators
~ $ CD tmp/A/B/C | mkdir-P tmp/A/B/C
You can also combine the control operators described in this section. Each operator affects the execution of the final command:
Listing 7. Examples of good habits 3: 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 Top
Exercise caution when referencing variables
Always use shell extensions and variable names with caution. Generally, it is best to include variable calls in double quotation marks unless you have enough reasons for not doing so. Similarly, if you use a variable name directly after a letter or number, make sure that the variable name is included in square brackets, to separate it from the surrounding region. Otherwise, shell interprets the trailing text as part of the variable name -- and may return a null value. Listing 8 provides examples of variables for reference and non-reference and their impact.
Listing 8. Example of good habits 4: Referencing (and not referencing) variables
~ $ Ls tmp/
A B
~ $ Var = "tmp /*"
~ $ Echo $ VaR
TMP/a tmp/B
~ $ Echo "$ Var"
TMP /*
~ $ Echo $ Vara
~ $ Echo "$ Vara"
~ $ Echo "$ {var}"
TMP/*
~ $ Echo $ {var}
TMP/
~ $
Back to Top
Use escape sequences to manage long input
You may have seen that the backslash (\) is used to extend a long row toCodeExamples, and you know that most shells treat the content you typed on subsequent rows connected by backslash as a single long line. However, you may not use this function in the command line as usual. If your terminal cannot properly process multi-line loopback, or your command line is smaller than usual (for example, when there is a long path in the prompt), The backslash is particularly useful. The backslash is also useful for understanding the meaning of long input lines, as shown in the following example:
Listing 9. Example of Good Habit 5: using 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 configurations:
Listing 10. alternative example of Good Habit 5: using 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 rows, shell always treats it as a single continuous row because it always deletes all backslash and extra spaces.
Note: In most shells, when you press the up arrow, the entire multi-line input will be re-painted to a single long input line.
Back to Top
Group commands in the list
Most shells have methods to group commands in the list so that you can pass their aggregate output down to a pipe or redirect any part or all of the streams to the same place. Generally, you can run a command list in a subshell or a command list in the current shell.
Run Command list in subshell
Use parentheses to include the command list in a single group. In this way, the command will be run in a new subshell, And you can redirect or collect the output of the entire group of commands, as shown in the following example:
Listing 11. Example of good habits 6: run the command list 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 archived content is extracted to the tmp/A/B/C/directory, and the output of the group command (including the list of extracted files) send the email to the admin address.
When you redefine the environment variables in the command list, and you do not want to apply those definitions to the current shell, subshell is preferred.
Run Command list in Current Shell
Enclose the command list with braces ({}) to run the command in the current shell. Make sure that there are spaces between the brackets and the actual commands. Otherwise, shell may not be able to correctly interpret the brackets. In addition, make sure that the last command in the list ends with a semicolon, as shown in the following example:
Listing 12. Another example of good habits 6: run the command list in the Current Shell
~ $ {CP $ {var} A. & chown-r guest. Guest &&\
> Tar CVF newarchive.tar A;} | mailx admin-s "new archive"
Back to Top
Use xargs outside find
Use the xargs tool as a filter to take full advantage of the output selected from the find command. The find operation usually provides a list of files that match certain conditions. This list is passed to xargs, which then uses this file list as a parameter to run some other useful commands, as shown in the following example:
Listing 13. Typical xargs usage examples
~ $ Find some-file-criteria some-file-path | \
> Xargs some-great-command-that-needs-filename-arguments
However, do not regard xargs as a helper tool for finding; it is one of the underutilized tools, and when you get into the habit of using it, you will want to perform all the experiments, it includes the following usage.
List of passed space Separation
In the simplest form of calling, xargs is like a filter that accepts a list (each member is on a separate row) as input. This tool places those members on rows separated by a single space:
Listing 14. Output example generated by xargs
~ $ Xargs
A
C
Control-d
A B C
~ $
you can send the output of any tool that outputs the file name through xargs to obtain the parameter list for some other tools that accept the file name as a parameter, as shown in the following example: