Why is sort -o useful?

UNIX philosophy says: do one thing and do it well. Make programs that handle text, because that is a universal interface.

The sort command, at least GNU sort, has an -o option to output to a file instead of stdout. Why is, say, sort foobar -o whatever useful when I could just sort foobar > whatever?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It is not just GNU sort that has it. BSD sort has it too. And as to why?
(I thought it was a good question too…)

From the man page:
“The argument given is the name of an output file to be used
instead of the standard output. This file can be the same as one
of the input files.”

You can’t go to the same file with redirection, the output redirection wipes the file.

To further clarify, if I wanted to sort a file and put the sorted results in the same place I might think to try sort < foo > foo. Except the output redirection truncates the file foo in preparation to receive the output. And then there is nothing to sort. Without “-o” the way to do it would be sort < foo > bar ; mv bar foo. I assume the -o option does something similar without making you have to worry about it.

Method 2

The ‘-o’ option was already in the the sort of the Sixth Edition of Unix

However I agree with you that it is not within the Unix philosophy. uniq did not have that option (and sort did not have a -u then).

On my PDP-11 I used a small program that would take one parameter:

renac whatever

If whatever already existed, it would write everything from stdin to a temporary file, that was only renamed to whatever after the stdin input dried up. That way you could pipe the output of any command into renac instead of redirecting to the filename without a chance of overwriting the input. Solving the overwriting problem in that way is IMHO more conform to the Unix philosophy.

Some later additions to the program were: not overwriting the output file if nothing had arrived on stdin (e.g. a result of mistyping part of the commandline), and allowing an option to append stdin to the named file.

This was one of the first (if not the first) real C programs that I made (for my job I mostly developed in Pascal on that system).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x