The 10 of UNIX ace habit
Tuesday, March 03, 2009 by rain
Use 10 the UNIX that can raise you%26reg;The good convention that commands an efficiency -- undesirable use mode is cast off in the process here.The technology that article successive ground coachs you learn a few to be used at commanding an operation,These technologies are first-rate,But normally by oversight.Know common error and the method that overcome them,So that you can cut understanding why to be worth to use these UNIX truly,be used to.
Foreword
When you often use a certain system,The use mode that often can be immersed in some kind to secure.Sometimes,You do not have nurturance with as far as possible the habit that best means works.Sometimes,Your undesirable habit can cause occurrence disorder even.One of optimal methods that correct this kind of defect,Use the good convention that boycotts these bad conventions conciously namely.The article put forward 10 the UNIX command that is worth to use is used to all right -- help you overcome a lot of common use eccentricity,Raise the good convention that commands a work efficiency in this process.Listed below this 10 good convention,Later more detailed to undertaking description.
Use 10 good convention
Ten when should use good conventions are:
- Catalog is founded to cultivate in single order.Change way;Do not want shift to file.Use command and control operator combination.Discretion cites variable.Alignment of use transferred meaning will manage longer input.Right in list command in group.In
find Use besidesxargs.Understand whengrep Should carry out computation -- when should bypass.The certain field in matching output,is right not merely advancing travel matchs.Stop to be oppositecat Use conduit.Catalog tree is founded in single order
Detailed list 1 demonstrated one of the commonnest UNIX bad habits:Define a catalog to cultivate.
Detailed list 1. The give typical examples of bad habit 1:Define every catalog tree alone
~ $ 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 $
Usemkdir -p It is easy that option founds all father catalog and its subdirectory to want in single order much.But although to knowing the manager of this option,They still also are manacled when commanding to subdirectory is founded on travel at founding every class subdirectory stage by stage.Beautiful time conciously nurturance this good convention is worthiness:
Detailed list 2. The give typical examples of good convention 1:Use a command to define catalog tree
~ $ mkdir -p tmp/a/b/c
You can use this option to found whole and complex catalog to cultivate (be special ideal is use in script) ,is to found simple hierarchy not merely.For example:
Detailed list 3. Another give typical examples of good convention 1:Use a command to define complex catalog tree
~ $ mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}
In the past,The only excuse that defines list alone is youmkdir Implementation does not support this option,But be no longer on most system such.IBM, AIX%26reg; ,mkdir, GNUmkdir And other observe standard of onefold UNIX (the system of Single UNIX Specification) has this option now.
To still lacking a few system of this function,You can be usedmkdirhier Script (refer to reference material please) ,This script executes same functionmkdir pack:
~ $ mkdirhier project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}
Change way;Do not want shift to file
Another undesirable use mode is file.tar the file is mobile to a certain catalog,Because this catalog is the catalog that you hope amid extracts.tar file fitly.Actually you need such doing far from.You can file any.tar follow one's inclinationsly file solution reduces any list -- this is-C The utility of option.Compress in solution a certain file when the file,Use-C Option will appoint the list that wants amid solution to compress this file:
Detailed list 4. The give typical examples of good convention 2:Use option - C will solve compress.tar to file file
~ $ tar xvf -C tmp/a/b/c newarc.tar.gz
Relative to the position that at will filing file shift hopes to you amid solution compresses it,Switch to this catalog,Just solve next compress it,Nurturance is used-C the habit is more desirable -- should file the file is located in other when a certain position especially such.
Use command and control operator combination
You may have known,In most Shell,You can go up to set a branch through be between the command all right in single order (;) will set an order.This semicolon is ShellControl operator,Although it is individual to be in,the command series connection that commands travel admiral disperse rises very useful,But it does not apply to all circumstances.For example,Assume you use semicolon to set two orders,Among them the second jussive is carried out correctly rely on the first jussive completely to be finished successfully.If the first commands what did not anticipate by you,exit in that way,The second command still can move -- the result can cause failure.Contrary,Should use properer control operator (the article will describe among them part operator) .The Shell that wants you only supports them,The habit that is worth nurturance to use them.
Return the zero ability when quiting position to run a certain command when another command only
Use%26amp;%26amp; Control operator will set two orders,So thatBecome only The first command returns the zero ability when quiting position to run the second command.In other words,If the first command runs a success,Criterion the second command will move.If the first commands failure,Criterion the second command does not move at all.For example:
Detailed list 5. The give typical examples of good convention 3:Use command and control operator combination
~ $ cd tmp/a/b/c %26amp;%26amp; tar xvf ~/archive.tar
The exemple is here medium,The content that file goes to extraction in ~/tmp/a/b/c catalog,Unless this catalog is nonexistent.If this catalog is nonexistent,Criteriontar The command won't move,Because this won't extract any content.
Return when another command only be not the zero ability when quiting position to run a certain command
Similar,|| Control operator space commands twice,And be returned when the first command only be not the zero ability when quiting position to run the second command.In other words,If the first commandsSuccessful,Criterion the second command won't move.If the first commands failure,Criterion the second commandJust meet Move.Checking a certain when giving catalog to whether exist,Use this operator normally,If this catalog is nonexistent,Found it:
Detailed list 6. Another give typical examples of good convention 3:Use command and control operator combination
~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c
The control operator that you still can combine the description in using this part.Every operator affects final order to move:
Detailed list 7. The assorted give typical examples of good convention 3:Use command and control operator combination
~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c %26amp;%26amp; tar xvf -C tmp/a/b/c ~/archive.tar
Discretion cites variable
Should use Shell to expand carefully from beginning to end with variable name.Had better call variable commonly include in double quote,Unless you have the sufficient argument that does not make so.Similar,If you are direct,variable name is used at the back of alphabetical number text,Ensure this variable the name includes to be in even square brackets ([] ) in,Come in order to make its and the text division all round separate.Otherwise,Shell will be explanation of text of follow at sb' heels the one part of variable name -- and return an empty value probably.All sorts of adduction that what detailed list 8 offerred variable and be not cite the give typical examples that reachs its to affect.
Detailed list 8. The give typical examples of good convention 4:Cite (and blame cite) variable
~ $ ls tmp/
a b
~ $ VAR=%26quot;tmp/*%26quot;
~ $ echo $VAR
tmp/a tmp/b
~ $ echo %26quot;$VAR%26quot;
tmp/*
~ $ echo $VARa
~ $ echo %26quot;$VARa%26quot;
~ $ echo %26quot;${VAR}a%26quot;
tmp/*a
~ $ echo ${VAR}a
tmp/a
~ $
Alignment of use transferred meaning will manage longer input
You had seen probably use turn over sprit (the code give typical examples that \) will come to continue longer travel to next group,And you know most Shell pass you the content that keys in on the follow-up travel that opposes sprit link to regard as individual long travel.However,You may not be in command travel resemble using this function in that way normally.If your terminal cannot handle much travel correctly to answer,circle,Or your command is compared all right normally small (there is long way classics below clew accord with for example when) ,Turn over sprit particularly useful.The meaning that the long input that turns over sprit to be keyed in to understanding goes is very useful also,Show like place of the following give typical examples:
Detailed list 9. The give typical examples of good convention 5:Will turn over sprit to be used at growing an input
~ $ cd tmp/a/b/c || \
%26gt; mkdir -p tmp/a/b/c %26amp;%26amp; \
%26gt; tar xvf -C tmp/a/b/c ~/archive.tar
Or,Also can use the following configuration:
Detailed list 10. Of good convention 5 replace give typical examples:Will turn over sprit to be used at growing an input
~ $ cd tmp/a/b/c \
%26gt; || \
%26gt; mkdir -p tmp/a/b/c \
%26gt; %26amp;%26amp; \
%26gt; tar xvf -C tmp/a/b/c ~/archive.tar
However,When differentiating the input to go up all right more all right when you,Shell regards his as individual and successive travel from beginning to end,Because it always deletes all turning over sprit and extra blank space.
Notice:In most Shell,Press when you up when arrowhead bolts,Whole many input goes to heavy draw on travel of individual long input.
Right in list command in group
Most Shell is had right in list command in group method,So that you can be down their total output,deliver a certain conduit,Or its any parts or flow entirely heavy directional to same place.You are general and OK through moving in a certain Subshell one commands list or through a command moving in current Shell list achieves this goal.
Command list runs in Subshell
Use bracket includes command list to be in single group.Such doing the command will move in a new Subshell,Allow you to weigh directional or collect whole group jussive to output,Show like place of the following give typical examples:
Detailed list 11. The give typical examples of good convention 6:Command list runs in Subshell
~ $ ( cd tmp/a/b/c/ || mkdir -p tmp/a/b/c %26amp;%26amp; \
%26gt; VAR=$PWD; cd ~; tar xvf -C $VAR archive.tar ) \
%26gt; | mailx admin -S %26quot;Archive contents%26quot;
In this give typical examples,This content that file goes to extraction in Tmp/a/b/c/ catalog,At the same time will in group jussive is outputted (the list that includes to extract a file) deliver an address through mailadmin.
In variable of environment of the redefine in commanding list when you,When and you do not hope using those definitions at current Shell,Use Subshell is more desirable.
Command list runs in current Shell
the order list uses big bracket ({}) draw together rises,In order to be inCurrent Move in Shell.Ensure blank space includes between bracket and actual order,Otherwise Shell cannot explain bracket correctly possibly.In addition,The last command that ensures list is medium even with semicolon ending,Show like place of the following give typical examples:
Detailed list 12. Another give typical examples of good convention 6:Command list runs in current Shell
~ $ { cp ${VAR}a . %26amp;%26amp; chown -R guest.guest a %26amp;%26amp; \
%26gt; tar cvf newarchive.tar a; } | mailx admin -S %26quot;New archive%26quot;
It is besides Find use Xargs
Usexargs The tool serves as choose implement,In order to make full use of fromfind The output that the command chooses.find Move to offer the file list that matchs with certain condition normally.This list is deliveredxargs Go up,Latter uses this file list to move as parameter next other and certain useful command,Show like place of the following give typical examples:
Detailed list 13. The classical usage give typical examples of Xargs tool
~ $ FindSome-file-criteria Some-file-path | \
%26gt; xargs
Some-great-command-that-needs-filename-arguments
However,Not willxargs Be being regarded only isfind auxiliary tool;It is an one of tools that did not get making full use of,When your nurturance uses its convention,Will hope to have all tests,Include the following use.
Deliver the list of blank space space
Be in the simplest in calling a form,xargs Choose like implement,It accepts a list (every member goes up in alone travel respectively) as the input.This tool places those members the travel in space of individual blank space to go up:
Detailed list 14. The output give typical examples that Xargs tool produces
~ $ xargs
a
b
c
Control-D
a b c
~ $
You can be sent throughxargs The output of any tools that will output file name,So that be other and certain the tool that accepts file master to be parameter obtains parameter list,Show like place of the following give typical examples:
Detailed list 15. The use give typical examples of 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 $
xargs The command is used at passing file name not merely.You return any moment in individual travel can choosing text version in need to use it:
Detailed list 16. The give typical examples of good convention 7:Tool of use Xargs will choose text version individual travel in
~/tmp $ ls -l | xargs
-rw-r--r-- 7 joe joe 12043 Jan 27 20:36 December_Report.pdf -rw-r--r-- 1 \
root root 238 Dec 03 08:19 README drwxr-xr-x 38 joe joe 354082 Nov 02 \
16:07 a -rw-r--r-- 3 joe joe 5096 Dec 14 14:26 archive.tar -rwxr-xr-x 1 \
joe joe 3239 Sep 30 12:40 mkdirhier.sh
~/tmp $
Discretion uses Xargs
Tell from the technology,Usexargs Encounter a trouble rarely.Below default circumstance,File end string is underline (_) ;If regard individual input as parameter this character,will send,Criterion all content after it will by oversight.To prevent this kind of circumstance happening,Can use-e Mark,It is banned completely below the case that does not take parameter with end string.
Understanding when Grep should carry out computation -- when should bypass
Avoid to pass conduit generalgrep Sendwc -l Will be opposite output linage computation.grep -c The computation that option offerred pair of travel that match with specific mode,And want commonly arrive than passing conduit to sendwc Faster,Show like place of the following give typical examples:
Detailed list 17. The give typical examples of good convention 8:Use and do not use the travel computation of 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
~ $
Besides rate factor,-c Option still is carried out enumerated good method.To many files,Belt-c Of optiongrep The alone computation that returns every file,Every a computation,And in the light ofwc the assorted total that conduit offers all documents is counted.
However,No matter whether consider rate,This give typical examples showed another wants to avoid the ground common error.These computation methods are offerred onlyInclude the linage that matchs pattern-- if that is the result that you should search,Problem of this it doesn't matter.But be expert at in below the circumstance of the many example that have a certain specific pattern,These methods cannot be offerred for you match actuallyExample amount actual count.In the final analysis,If want to example computation,You still want to usewc Come computation.Above all,Use-o Option (if your version supports it) will movegrep Command.This optionOnly The pattern that output matchs,Every a mode,And do not output an itself.But you cannot will it and-c Option union is used,Because this wants to usewc -l Come to travel computation,Show like place of the following give typical examples:
Detailed list 18. The give typical examples of good convention 8:Use Grep is right mode example computation
~ $ grep -o and tmp/a/longfile.txt | wc -l
3402
~ $
The exemple is here medium,Callwc Want to be called than the secondgrep Insert a fictitious mode (for examplegrep -c) will undertake matching mixing to going computation is a bit a bit faster.
The certain field in matching output,is right not merely advancing travel matchs
In hoping to match output to go only when youSpecific field When medium mode,Such asawk Wait for a tool to want excelgrep.
The file that demonstrated how to list 12 month has been revised only through simplifying give typical examples below.
Detailed list 19. The give typical examples of bad habit 9:Use Grep will search the mode in specific field
~/tmp $ ls -l /tmp/a/b/c | grep Dec
-rw-r--r-- 7 joe joe 12043 Jan 27 20:36 December_Report.pdf
-rw-r--r-- 1 root root 238 Dec 03 08:19 README
-rw-r--r-- 3 joe joe 5096 Dec 14 14:26 archive.tar
~/tmp $
In this give typical examples,grep To undertaking filtration all right,Output its are taken in modification date and nameDec all files.Because of this,The file such as such as December_Report.pdf is match,Although it since had not revised since one month.This may not be the result that you hope.To match the pattern in specific field,Had better useawk,Accord with of among them operation of a relation undertakes matching to exact field,Show like place of the following give typical examples:
Detailed list 20. The give typical examples of good convention 9:Use Awk will search the mode in specific field
~/tmp $ ls -l | awk '$6 == %26quot;Dec%26quot;'
-rw-r--r-- 3 joe joe 5096 Dec 14 14:26 archive.tar
-rw-r--r-- 1 root root 238 Dec 03 08:19 README
~/tmp $
About how to useawk more and detailed information,Refer to reference material please.
Stop to use pipeline to Cat
grep A common main use error is to pass conduit generalcat output is sentgrep In order to search the content of individual file.This is needless absolutely,It is wasteful time purely,Because of such asgrep Such tool accepts file master to be parameter.You need to be used below this kind of circumstance far fromcat,Show like place of the following give typical examples:
Detailed list 21. The give typical examples of good convention and bad habit 10:Use the Grep that take and does not take 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 mistake consist in in a lot of tools.Because most tool accepts use hyphen (- ) standard input serves as a parameter,Accordingly although usecat Will dispersestdin Medium many files,Parameter also is invalid normally.Use when you only belt many choose one of optioncat When,Just be necessary to carry out join above all before conduit truly.
Last word:Nurturance good convention
Any in commanding a habit undesirable use pattern that had better examine you.The rate that undesirable use mode can lower you,The mistake outside and can guide normally presenting his compliment.The article introduced 10 new convention,They can help you cast off a lot of the commonnest use errors.Nurturance the positive step that these good conventions are the technical ability of travel of UNIX command that enhances you.
Textual link:Http://www.ibm.com/developerworks/cn/aix/library/au-badunixhabits.html