Shell Command Line – Why `sort < "$f1"` is Preferred Over Other Sort Commands

argumentscommand lineio-redirectionshell

From https://unix.stackexchange.com/a/458074/674

Remember to use -- when passing arbitrary arguments to commands (or use redirections where possible). So sort -- "$f1" or better sort < "$f1" instead of sort "$f1".

Why is it preferred to use -- and redirection?

Why is sort < "$f1" preferred over sort -- "$f1"?

Why is sort -- "$f1" preferred over sort "$f1"?

Thanks.

Best Answer

sort "$f1"

fails for values of $f1 that start with - or here for the case of sort some that start with + (can have severe consequences for a file called -o/etc/passwd for instance).

sort -- "$f1"

(where -- signals the end of options) addresses most of those issues but still fails for the file called - (which sort interprets as meaning its stdin instead).

sort < "$f1"

Doesn't have those issues.

Here, it's the shell that opens the file. It also means that if the file can't be opened, you'll also get a potentially more useful error message (for instance, most shells will indicate the line number in the script), and the error message will be consistent if you use redirections wherever possible to open files.

And in

sort < "$f1" > out

(contrary to sort -- "$f1" > out), if "$f1" can't be opened, out won't be created/truncated and sort not even run.

To clear some possible confusion (following comments below), that does not prevent the command from mmap()ing the file or lseek()ing inside it (not that sort does either) provided the file itself is seekable. The only difference is that the file is opened earlier and on file descriptor 0 by the shell as opposed to later by the command possibly on a different file descriptor. The command can still seek/mmap that fd 0 as it pleases. That is not to be confused with cat file | cmd where this time cmd's stdin is a pipe that cannot be mmaped/seeked.

Related Question