bashsorting

Why does in-place sort of same file fail?


The sort command doesn't behave as expected when redirecting with stdout as stated here: [sort command question] (Bash Sorting Redirection)!

My question is, why does the following fail?

sort file > file       # Surprise! Generates empty file. Data is lost :(

Does it have to do with write permissions with the shell in specific distros or is it something else? If it is only a write permission problem, how can it be made to work (not that it should be made to work)? Shouldn't file just be overwritten first?


Solution

  • The shell sets up the redirection before the command runs and when the shell opens the file for writing it immediately truncates the contents of the file. sort never has a chance to see them.

    From the bash man page:

    Redirection

    Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection may also be used to open and close files for the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.