Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Command Starting with ">"

Tags:

bash

shell

I recently came across a shell command that looked like this: "> outfile < infile cat", which appears to be functionally equivalent to "cat infile > outfile". For that matter, the general form seems to be "> outfile < infile command arg1 ... argN" becomes "command arg1 ... argN infile > outfile".

Anyway, I was wondering if anyone could elaborate on how the leading ">" achieves this effect, and if there are any practical uses for it.

like image 676
Ryan Avatar asked Apr 17 '12 05:04

Ryan


People also ask

What are the shell commands?

The shell is the command interpreter on the Linux systems. It the program that interacts with the users in the terminal emulation window. Shell commands are instructions that instruct the system to do some action.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is $() in shell script?

Seems like ${variable} is the same as $variable , while $() is to execute a command.


2 Answers

The "Bash Reference Manual" says the following about the redirection operators:

The following redirection operators may precede or appear anywhere within a simple command or may follow a command.

So the following commands are all equivalent:

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

Though I'd guess that the first is most common form.

Note that the relative order of redirections is significant, so if you're redirecting one file descriptor to another, for example, the following would 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
like image 154
Michael Burr Avatar answered Oct 10 '22 12:10

Michael Burr


The ">" simply redirects the output of the command to the file given as the next argument. The typical use is to append this at the end of the command but it can be in any place. So:

> outfile <command> is equivalent to <command> > outfile. Same holds true for the input redirection.

Please note that in the above examples <command> is not some weird syntax - it simply replaces arbitrary command.

like image 4
Ivaylo Strandjev Avatar answered Oct 10 '22 12:10

Ivaylo Strandjev