Ubuntu – When should I use < or <() or << and > or >()

bashcommand lineredirect

I know that <, <(), << all are used to give input and >, >() which are used to redirect output.

But I don't know what is clear difference between them and when to use them.
Please explain in detail and along with references if possible. Thanks

Best Answer

"When to use" is really dependant on you're doing. It's like asking when to use a Phillips or a slothead screwdriver. I can tell you what they all are, and what they do, but working out when you'd use each one, is up to you.

All of these are extensively documented in the TLDP Advanced Bash Scripting Guide. If you need examples, that's the place.

  • < filename reads from a file into STDIN
  • > filename writes STDOUT to file, overwriting anything.
  • >> filename writes STDOUT to file, appending if it already exists.
  • <(command) absorbs the output of the internal command and provides a filename
  • >(command) provides a filename to the outer command but actually redirects anything written to it to the STDIN of the internal command.
  • <<TOKEN is a here document, aka heredoc. It'll read anything that follows into STDIN until it sees TOKEN again. It's useful for multi-line content. It has to be followed by a newline. Unless you quote the token, heredocs support variable substitution.
  • <<-TOKEN is as above except that it will ignore leading tabs (but only tabs). This is handy to preserve source formatting but it really does only work with tabs. It's rendered useless on Stack Exchange sites because they substitute tabs for spaces :(
  • <<"TOKEN" is a heredoc that won't substitute $variables.
  • <<<"string" is a herestring. It's read into STDIN. This can do variable substitution.
  • | command joins the current STDOUT to the STDIN of command
  • |& command joins STDOUT and STDERR onto the STDIN of command (useful for grepping error output)
  • 1> and 2> are used to explicitly redirect STDOUT and STDERR. > implies 1> so you rarely see it used explicitly.
  • In a similar vein >&1 and >&2 can be used to redirect into STDOUT and STDIN.
  • /dev/std{in,out,err} also exist as symlinks to the basic in/out/error file descriptors. This is dead handy when something will only accept a filename argument but you want it to write to STDOUT, for example.