I am trying to understand the differences between these two similar commands.
aa=$(foo | bar | head -1)
read aa < <(foo | bar | head -1)
<()
requires #!/bin/bash
, but does that make it slower?bash
or sh
processes?I am looking to use the command with the best performance.
In computing, process substitution is a form of inter-process communication that allows the input or output of a command to appear as a file. The command is substituted in-line, where a file name would normally occur, by the command shell.
This command takes a line from standard input (usually your keyboard) and assigns consecutive words on that line to any variables named. For example: read first init last takes an input line of the form: J. Q. Public and has the same effect as if you had typed: first=J. init=Q. last=Public.
Command substitution is a mechanism that is followed by programmers in a shell script. In this mechanism, the output of a command replaces the command itself. Shell operates the expansion by executing a command and then replacing the command substitution with the standard output of the command.
The command substitution $(cat file ) can be replaced by the equivalent but faster $(< file ) . When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by ' $ ', ' ` ', or ' \ '.
lastpipe
is not enabled, there is a process for each pipeline element plus a subshell for either substitution plus the parent process.lastpipe
is enabled, the last element of the pipeline will exec
without forking in both cases, still requiring the same number of processes./dev/fd/*
, the shell will create named pipes for process substitutions instead. This likely affects performance.$(<...)
in everything except Bash that supports it). In mksh and ksh93, there's also the ${ ;}
style command substitution, but each shell implements this differently. In ksh93, it may or may not give a speedup. in mksh, probably not. mksh doesn't support process substitutions, and zsh doesn't support (and has no way of simulating) BASHPID
, so I haven't looked into it.There is nothing intrinsically faster about a command substitution than a process substitution in Bash, but the head
is redundant in the case of read
since you're only reading a single line there. As an aside, always use head -n ...
-- -1
is not portable. Also, don't use read
without -r
unless you want the shell to mangle the input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With