Skip to main content
1 of 4
terdon
  • 252.9k
  • 69
  • 481
  • 720

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. For example:

$ 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 

So, there is no better or worse option, they are just useful in different context. If both work for you, feel free to choose whichever you prefer.

terdon
  • 252.9k
  • 69
  • 481
  • 720