Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about some standard input or heredoc usage in shell

Tags:

linux

bash

shell

enter image description here

As the image. All commands are similar. I know how to use that, but I don't really know the detail. Would anyone know that? Thank you very much.

# does `cat` read fd and print?
$ cat file

# does `cat` read from stdin and print?
$ cat < file

$ cat - < file

# with heredoc or herestring, what methods `cat` command use to read from heredoc?stdin?

$ cat << EOF
heredoc> test
heredoc> EOF
test

$ cat <<< "test"

$ cat - << EOF
heredoc> test
heredoc> EOF
test

$ cat - <<< "test"

# and I dont why these commands works?

$ cat <(echo "test")

$ cat - <<(echo "test")

# why this command doesn't work?

$ cat - <(echo "test")
like image 595
Shawn Huang Avatar asked Oct 16 '25 02:10

Shawn Huang


1 Answers

Some reading material, all from the very useful Bash manual:

  • Redirection (<filename) -- causes standard input to be redirected to the file filename

  • Here documents (<<WORD) -- causes standard input to be redirected to the script source from the next line, up to but not including the line WORD

  • Here strings (<<<"string") -- causes standard input to be redirected to the string string (as though the string were written to a temporary file and then standard input redirected to that file)

  • Process substitution (<(command)) -- starts a process executing command and inserts a name onto the command line which acts like a filename, such that reading from that "file" produces the output of the command

The use of - to indicate the the source file is standard input is common to many commands and recommended by Posix. Many commands read from standard input if no file is specified. Some, like cat, implement both ways of indicating that the intention is to read from standard input.

Note that - and <(command) are both filename arguments, while <filename, <<WORD and <<<"string" are redirections. So while they superficially look similar, they are quite different under the hood. What they have in common is that they have to do with input; some of them (but not here-docs/strings) have analogues that have to do with output, using > instead of <.

like image 138
rici Avatar answered Oct 18 '25 16:10

rici