1

I don't understand what is the difference b/w ls 2>tmp >tmp and ls > tmp. They both seem to do essentially the same thing, creating a file tmp and storing the result of ls command.

4
  • 1
    You seem to be asking two separate questions here. Commented May 27, 2014 at 3:32
  • 1
    ls >2 >tmp1 >tmp1 doesn't appear to be a valid command. Commented May 27, 2014 at 3:32
  • You are basically with the ls >2 > tmp1 > tmp1 script command taking the command ls sending the output to a file named 2 (if it is not there create it) which doesn't write to the file 2, but sends it to a file tmp1 (if it is not there create it), does not write to tmp1, but sends that output to tmp1 (if it is not there create it), then the output settles in tmp1. tl;dr You make a blank file 2 have an extra > tmp1 and output ls to tmp1. (Could you split this into 2 questions as well?) Commented May 27, 2014 at 3:49
  • @NoTime I have updated the question Commented May 27, 2014 at 4:13

2 Answers 2

5

A short answer: ls 2>tmp >tmp redirect both stdout and stderr to file tmp. while ls > tmp only redirect stdout to file tmp.

Try this to see the difference:

$ ls asdsadasd 2>tmp >tmp
$ cat tmp
ls: cannot access asdsadasd: No such file or directory

$ ls asdsadasd > tmp
ls: cannot access asdsadasd: No such file or directory
$ cat tmp
<Nothing happen here>
0
3

Note that you should not do:

ls 2> tmp > tmp

Above the shell opens tmp for writing on file descriptor 2, then it opens tmp for writing again on file descriptor 1 and then executes ls. You'll have two file descriptors pointing to two separate open file descriptions to the same file.

If ls writes on both its file descriptor 1 (stdout for the file list) and file descriptor 2 (stderr for the error messages), those outputs will overwrite each other (assuming tmp is a regular file and not a named pipe).

Actually, the stdout output will be buffered, so is more likely to be written at the end before ls exits, so it will overwrite the stderr output.

Example:

$ ls /x /etc/passwd 2> tmp > tmp
$ cat tmp
/etc/passwd
ccess /x: No such file or directory

You should use:

ls > tmp 2>&1

or

ls 2> tmp >&2

In that case, the shell opens tmp on fd 2 and then duplicates that fd onto fd 1, so both fd 1 and 2 will share the same open file description to tmp and outputs won't overwrite each other.

$ ls /x /etc/passwd 2> tmp >&2
$ cat tmp
ls: cannot access /x: No such file or directory
/etc/passwd

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.