help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Why `$(<` is slow?


From: Stephane Chazelas
Subject: Re: [Help-bash] Why `$(<` is slow?
Date: Fri, 30 Aug 2019 07:50:55 +0100
User-agent: NeoMutt/20171215

2019-08-29 20:39:15 -0500, Peng Yu:
[...]
> `$(<` is just a little faster than `$(cat`. Is I guess `$(<` involves
> a subshell? But shouldn't subshell be optimized away in such a case?
[...]

Yes, bash is the only shell where it's not optimised away. There
is no subshell involved in ksh (the original implementation),
zsh or pdksh/mksh.

mksh also added a $(<<EOF
qwqewe
EOF) form of the operator which in effect acts like a quoting
operator.

In any case, in all shells, all trailing newlines are removed
like in command substitution.

In bash, $(<qwe) still creates a pipe, forks a child process
that reads from the file, writes to the pipes, while the parent
read from the other end of the pipe. The only thing that is
optimised away is the execution of "cat".

Note that IFS= read -rd '' x (you forgot the IFS= btw) stops at
the first NUL in the input while $(<file) removes all the NULs
(in bash). zsh is the only shell that can store NULs in its
variables.

zsh also has a $mapfile[file] special associative array (in the
zsh/mapfile module loaded with zmodload zsh/mapfile) that uses
mmap() to access the file (it's not as effecient as you would
hope as zsh still duplicates the data on the heap to do the NUL
escaping).

See also the readarray builtin (also confusingly called mapfile)
in bash to read a file's lines into an array (also supports
NUL-delimited records since 4.4).

You can find more details about $(<file) at
https://unix.stackexchange.com/questions/189749/understanding-bashs-read-a-file-command-substitution/368663#368663

-- 
Stephane




reply via email to

[Prev in Thread] Current Thread [Next in Thread]