Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference beetwen $ echo Hello world > file and $ echo Hello > file world in bash?

$ echo Hello world > file
$ echo Hello > file world
$ echo > file Hello world
$ > file echo Hello world

They all do the same thing, but I do not know why.

like image 728
Jesús Rafael Zúñiga Castro Avatar asked Oct 22 '15 21:10

Jesús Rafael Zúñiga Castro


People also ask

How do I echo to a text file?

The echo command prints the strings that are passed as arguments to the standard output, which can be redirected to a file. To create a new file run the echo command followed by the text you want to print and use the redirection operator > to write the output to the file you want to create.


1 Answers

From man bash:

   Simple Commands
       A  simple  command  is a sequence of optional variable assignments fol-
       lowed by blank-separated words and redirections, and  terminated  by  a
       control operator.  The first word specifies the command to be executed,
       and is passed as argument zero.  The  remaining  words  are  passed  as
       arguments to the invoked command.

That is, it doesn't specify the ordering of the "words and redirections". Later in the REDIRECTIONS section:

REDIRECTION
       [...]
       The [...] redirection  opera-
       tors may precede or appear anywhere within a simple command or may fol-
       low a command.  Redirections are processed in the  order  they  appear,
       from left to right.
       [...]

So they can appear anywhere.

And as you yourself have observed too, there's no difference between them in terms of the result. There is a difference however in readability.

This is the most intuitive way of writing it:

echo Hello world > file

Really easy to understand. The > looks like an arrow, doesn't it.

The others are not so intuitive, less readable. I suggest to stick to the first writing style.

like image 151
janos Avatar answered Sep 28 '22 18:09

janos