Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `sort file > file` result in an empty file? [duplicate]

Tags:

bash

When you try to sort a file in-place with

sort afile > afile

you silently end up with afile being an empty file.

Why is that? I'd expect either an error or the original contents, but sorted. I haven't tested other shells.

Upvotes for one-liners that do perform the expected behaviour.

PS bash redirect input from file back into same file doesn't address the "why" at all. I know I can go around it with a temporary file. I am interested in what happens. The upvotes for one-liners part was an afterthought in search of shorter ways.

like image 366
Chris Wesseling Avatar asked Dec 20 '22 03:12

Chris Wesseling


1 Answers

With sort afile > afile this happens:

  1. The shell opens and truncates afile because of the file direction operation > afile

  2. The shell executes the sort program with one argument, afile, and binds stdout of the new process to the file descriptor opened in step 1.

  3. The sort program opens the file given as its first argument, which is empty due to the truncation happening in step 1.

You can do it with sort afile -o afile

like image 126
nos Avatar answered Feb 20 '23 06:02

nos