14

Could someone explain me this syntax for mapfile input redirection?

mapfile -t array < <(./inner.sh)

(from this StackOverflow answer by gniourf_gniourf)

As I understand, the first "<" is to take input from the output of whatever is on the right side of it. But what is the <( ... ) syntax? Why is the second "<" required?

Community
  • 1
  • 1
Sujay Phadke
  • 2,145
  • 1
  • 22
  • 41
  • 2
    It's called [Process substitution](http://tldp.org/LDP/abs/html/process-sub.html) – anishsane Apr 16 '15 at 04:07
  • 1
    Thanks. so I looked at the link you mentioned. In that, the example for 'wc' uses a single <( ... ). So why is the extra "<" required in the mapfile case for taking in input? – Sujay Phadke Apr 16 '15 at 04:10
  • 2
    From the perspective of the process wc, the example uses `wc filename` syntax. `<(...)` is process substitution syntax. From logical perspective, `<(...)` gets expanded to a filename, & anything read from that file is the output of command between the parenthesis. You can check other examples on that page or try your own examples. – anishsane Apr 16 '15 at 04:13

1 Answers1

21

The reason the linked example looks like this:

wc <(cat /usr/share/dict/linux.words)

And the mapfile answer looks like this:

mapfile -t array < <(./inner.sh)

Is because of the difference in the wc and mapfile commands and how the substituted process needs to be given to command.

As anishsane says the expansion of <(command) is a filename and can be used anywhere a filename can be used.

wc takes filenames as arguments so it can be used directly as an argument.

mapfile reads from standard input so to get it to read from a specific file you use you redirect standard input from the file </path/to/somefile but as I just said the expansion of <(command) is a filename so you can use that in the input redirection.

However, you cannot just concat the two bits directly (the way you can with a file name/path) because << is also a valid shell construct (a here document) and that would be ambiguous to the shell. So to avoid that you need to space out the two < characters and end up with < <(command) (which is analogous to < file which is perfectly legal).

Community
  • 1
  • 1
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148