0

Both show the sorted file without changing the original file, so what is the difference?

  • 1
    Not all of that applies to `sort`, of course (like showing filenames and so on), but most of it does: `sort` reads from stdin if no file is given, just like grep, and using filenames allow you to sort the combined input from multiple filenames. – muru Jun 22 '23 at 03:35
  • does this answer your question [What’s the difference between providing input to a command via an argument to that command and providing input through a shell redirection operator?](https://unix.stackexchange.com/q/564069/72456) – αғsнιη Jun 22 '23 at 03:44
  • See also [Why is \`sort < "$f1" \` preferred over \`sort -- "$f1"\`, and why is this preferred over \`sort "$f1"\`?](//unix.stackexchange.com/q/458265) – Stéphane Chazelas Jun 22 '23 at 05:09

1 Answers1

1

The differences are:

With

sort < filename

the parent shell opens filename, and connects it to sort's STDIN I/O stream. sort runs, sees no command line filenames, and simply reads STDIN and sorts.

With

sort filename

sort notices a command line parameter, opens filename, and sorts.

waltinator
  • 4,439
  • 1
  • 16
  • 21
  • See also [Why is \`sort < "$f1" \` preferred over \`sort -- "$f1"\`, and why is this preferred over \`sort "$f1"\`?](//unix.stackexchange.com/q/458265) for some advantages with using redirection. – Stéphane Chazelas Jun 22 '23 at 05:10
  • 1
    Note that shells open `filename` in the process in which they will run `sort`, not the parent (and do not run `sort` if the file cannot be opened). – Stéphane Chazelas Jun 22 '23 at 05:16
  • @StéphaneChazelas I looked at the `bash` source, years ago, and redirection **is** done in the parent shell. That's why `sudo echo "foo" >>/etc/fstab` FAILS and `echo "foo" | tee -a /etc/fstab` works. What's your source for "opening redirection in the process, not the parent"? Are you familiar with `man fork exec ld.so`? – waltinator Jun 23 '23 at 00:08
  • It's definitely the shell that opens the file (what else would do it?). What I'm saying is that the shell does it in the child process in which it will later execute the command, not in the parent process. I'm just objecting to the word *parent* which may be misleading here. Just say *the shell opens filename...*. Try `strace -ffo trace.out bash -c 'uname > out; exit'` to verify – Stéphane Chazelas Jun 23 '23 at 05:59