" I recently met a shell command that looked like this: "> outfile

Shell Command Starting with ">"

I recently met a shell command that looked like this: "> outfile <infile cat", which appears to be functionally equivalent to "cat infile> outfile". In this case, the general form looks like "> outfile <infile command arg1 ... argN" becomes "the command arg1 ... argN infile> outfile".

In any case, I was wondering if anyone could understand how the host ">" achieves this effect, and if there are any practical applications for it.

+7
source share
5 answers

The Bash Reference Guide reports the following about redirection operators:

The following redirection operators may precede or appear at any point in a simple command, or may follow a command.

Thus, the following commands are equivalent:

ls -al > listing.txt > listing.txt ls -al ls > listing.txt -al 

Although I would suggest that the first most common form.

Note that the relative reordering order is significant, so if you redirect one file descriptor to another, for example, the following will be different:

 ls > listing.txt 2>&1 # both stdout and stderr go in to listing.txt ls 2>&1 > listing.txt # only stdout goes to listing.txt, because stderr was made # a copy of stdout before the redirection of stdout 
+6
source

">" simply redirects the output of the command to the file specified as the next argument. A typical use is to add this at the end of the command, but it can be anywhere. So:

> outfile <command> equivalent to <command> > outfile . The same is true for input redirection.

Note that in the above examples, <command> not some weird syntax - it just replaces an arbitrary command.

+4
source

The equivalent is not:

 cat infile > outfile 

Rather it is

 cat < infile > outfile 

(only in case of cat, cat infile matches cat <infile )

Once you see this, the original command seems simpler.

+1
source

One note. This is because you can really write it

 < file command 

this makes useless use of Cat all the more unforgivable:

 cat file | command 

That is, even if for some reason you want the file to be syntactically located to the left of the command, you still do not need cat !

+1
source

To redirect the output, a leading value greater than the sign (>) is used. By default, it redirects STDOUT. In this case, STDOUT is empty and, therefore, a new and empty file is created (a similar effect for touch output ).

You can also use this command style to delete existing files, i.e.

  $ echo FOO >/tmp/foo $ ls -l /tmp/foo -rw-r--r-- 1 flah wheel 4 Apr 17 01:49 /tmp/foo $ > /tmp/foo $ ls -l /tmp/foo -rw-r--r-- 1 flah wheel 0 Apr 17 01:49 /tmp/foo $ 

See the redirecting section of the bash man page for more information.

0
source

All Articles