This article presents 10 UNIX command line habits that are worth using & mdash; to help you overcome many common usage quirks and improve the working efficiency of the command line. These 10 good habits are listed below, and a more detailed description is given later. The ten good habits to use are: create a directory tree in a single command. Change the path. This article introduces 10 UNIX command line habits that are worth using-this helps you overcome many common usage quirks and improve the working efficiency of the command line 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
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
Listing 3. another example of good habit 1: using a command to define a complex directory tree
~ $ Mkdir-pproject/{lib/ext, bin, src, doc/{html, info, pdf}, demo/stat/}
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.
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,
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
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/
~ $
Use escape sequences to manage long input
You may have seen a code example that uses a backslash (\) to extend a long line to the next line, in addition, 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.
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.
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.
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 "Newarchive"
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
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
B
C
Control-D
A B c
~ $
You can send the output of any tool that outputs file names through xargs to obtain the parameter list for some other tools that accept file names as parameters, as shown in the following example:
Listing 15. example of xargs
~ /Tmp $ ls-1 | xargs
December_report1_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 only used to pass file names. You can also use it whenever you need to filter text into a single row:
Listing 16. example of good habit 7: use xargs to filter text to a single row
~ /Tmp $ ls-l | xargs
-Rw-r -- 7 joe 12043 Jan 27 December_Report.pdf-rw-r -- r -- 1 \
Root 238 Dec 03 README drwxr-xr-x 38 joe 354082 Nov02 \
A-rw-r -- 3 joe 5096 Dec 14 archive.tar-rwxr-xr-x 1 \
Joe 3239 Sep 30 mkdirhier. sh
~ /Tmp $
Avoid sending grep to wc-l in a pipeline to count the number of output rows. The-c option of grep provides a count of rows that match a specific pattern and is generally faster than sending data to wc through pipelines, as shown in the following example:
Listing 17. example of good habit 8: Using and without grep row counting
~ $ Time grep and tmp/a/longfile.txt | wc-l
2811
Real 0m0. 097 s
User 0m0. 006 s
Sys 0m0. 032 s
~ $ Time grep-c and tmp/a/longfile.txt
2811
Real 0m0. 013 s
User 0m0. 006 s
Sys 0m0. 005 s
~ $
In addition to the speed factor, The-c option is a good way to execute the count. For multiple files, grep with The-c option returns a separate count for each file, with one count per row. for wc pipelines, the total number of combinations of all files is provided.
However, regardless of the speed, this example shows another common error to be avoided. These counting methods only provide the number of rows that contain the matching mode-if that is the result you are looking for, this is no problem. However, when a row has multiple instances in a specific mode, these methods cannot provide you with a real count of the number of instances actually matched. In the final analysis, you still need to use wc to count instances. First, run the grep command using the-o option (if your version supports it. This option only outputs the matching mode. each line has one mode without losing the trip itself. However, you cannot use it with the-c option. Therefore, you must use wc-l to count rows, as shown in the following example:
Listing 18. example of good habit 8: using grep to count mode instances
~ $ Grep-o and tmp/a/longfile.txt | wc-l
3402
~ $
In this example, grep filters rows and outputs all the files with Dec in the modification date and name. Therefore, files such as December_Report.pdf match, even if they have not been modified since January. This may not be the expected result. To match the pattern in a specific field, it is best to use awk. one of the relational operators matches the exact field, as shown in the following example:
Listing 20. examples of good habits 9: use awk to find the pattern in a specific field
~ /Tmp $ ls-l | awk '$6 = "Dec "'
-Rw-r -- 3 joe 5096 Dec 14 14 14: 26archive.tar
-Rw-r -- 1 root 238 Dec 03 08: 19 README
~ /Tmp $
A common basic usage error of grep is that cat output is sent to grep in a pipeline to search for the content of a single file. This is absolutely unnecessary. it is a waste of time, because tools such as grep accept file names as parameters. You do not need to use cat in this case, as shown in the following example:
Listing 21. examples of good habits and bad habits 10: use grep with or without cat
~ $ Time cat tmp/a/longfile.txt | grep and
2811
Real 0m0. 015 s
User 0m0. 003 s
Sys 0m0. 013 s
~ $ Time grep and tmp/a/longfile.txt
2811
Real 0m0. 010 s
User 0m0. 006 s
Sys 0m0. 004 s
~ $