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.

Upvotes: 5

Views: 2081

Answers (1)

janos
janos

Reputation: 124724

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.

Upvotes: 5

Related Questions