Neither is better, they just have different use cases. First of all, not all programs write to standard output, so sometimes you must use their option to provide an output file name. Conversely, not all programs have such an option, so sometimes you must redirect.
More generally, in the cases where you have the choice, you can use whichever you prefer for what you are doing. If, for example, you are running the command as a different user using sudo
, then the redirection will be run as your regular user and won't have the elevated privileges conferred by sudo
:
$ sudo curl unix.stackexchange.com > /unix.se
bash: /unix.se: Permission denied
This is because the redirection, the >
, isn't part of curl
, so has no connection with the sudo
and is being run as your regular user. This is also why the error appears even before I am prompted for a password. So here, using curl's -o
is one possible way around that problem:
$ sudo curl unix.stackexchange.com -o /unix.se
[sudo] password for terdon:
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 167 100 167 0 0 3037 0 --:--:-- --:--:-- --:--:-- 3092
Conversely, if for instance you want to append multiple pages to one file, then you can't use -o
because that will overwrite the file's contents:
$ for url in unix.stackexchange.com google.com duckduckgo.com; do
curl -o mysites.all "$url" 2>/dev/null
done
$ grep -ic '<head>' mysites.all
1
As you can see above, we only have one <head>
tag in the output file, because each iteration overwrote the previous contents. If we were to instead redirect output using >
, we would get everything:
$ for url in unix.stackexchange.com google.com duckduckgo.com; do
curl "$url" 2>/dev/null
done > mysites.all
$ grep -ic '<head>' mysites.all
3
On the other hand, sort
has the -o
option which writes the output file only after processing all the input, allowing to use a same file for both input and output. This can't be done with a redirection, as the shell will open and truncate the output file even before starting the command itself.
So, there is no better or worse option, they are just useful in different contexts. If both work for you, feel free to choose whichever you prefer.
command > file
you are only redirecting STDOUT, the status codes will still be shown.