Yes, kind of. You can put a command substitution pretty much anywhere, and you can put a comment in a command substitution. It's ugly, but it works.
export\
$(# Comment
) \
var1=a\
var2=b $(# Comment
) \
var3=c
However, it's something you'd do if you really can't do it another way. In almost every case where you could do this, it's more readable to split the command into multiple parts, with comments attached to each part if necessary. Some comments might not even be necessary if you pick sensible variable names.
It's definitely not something you'd do for performance. Calling an external command is somewhat expensive, but calling a built-in command isn't. It's unlikely that splitting an export
command makes an observable difference to the time it takes to run your .zshrc
. (I benchmarked below, and it actually does make a difference if you benchmark that one line, but on the scale of a typical .zshrc
, this is completely negligible.) In any case, calling a built-in command is cheaper than a command substitution, so the $(…)
thing above will make your script slower.
Is calling export
for each variable slower than calling it once per variable? Yes, a little bit. At least for the particular code, version and platform I tested: the difference is small enough that it could vary.
% time zsh -c 'for ((i=0; i<$1; i++)) { export var1=foo var2=bar; }' 1 1000000
zsh -c 'for ((i=0; i<$1; i++)) { export var1=foo var2=bar; }' 1 1000000 1.36s user 0.24s system 99% cpu 1.612 total
% time zsh -c 'for ((i=0; i<$1; i++)) { export var1=foo; export var2=bar; }' 2 1000000
zsh -c 'for ((i=0; i<$1; i++)) { export var1=foo; export var2=bar; }' 2 1.67s user 0.43s system 99% cpu 2.097 total
However, adding a command substitution makes it 100 times slower! (Note the reduced number of iterations.)
% time zsh -c 'for ((i=0; i<$1; i++)) { export var1=foo var2=bar $(); }' 3 10000
zsh -c 'for ((i=0; i<$1; i++)) { export var1=foo var2=bar $(); }' 3 10000 1.33s user 1.00s system 107% cpu 2.165 total
export
is a shell builtin that does nothing except put the variable in the environment. it is very, very fast, especially compared to invoking any external command. Just use separate export commands. – Chris Down Mar 11 '24 at 00:27alias
just as fast? My zshrc contains a similarly formatted alias command for every single alias I have – Andy3153 Mar 11 '24 at 00:48export
command is? I'd guess that most programs don't call export very often, they likely do it just once for preparation, outside any loops and such. – ilkkachu Mar 11 '24 at 08:19time export var1=...
does not work – Andy3153 Mar 11 '24 at 08:42time
on a{ ..command block.. }
does work, though, so you cantime
one or 1000 exports. – Paul_Pedant Mar 11 '24 at 09:10time { export foo=bar; }
works in Bash, but there's some quirks with it on zsh. Using a subsell seems to work:time ( for ((i=0; i < 1000000; i++)); do export foo=bar; done )
. – ilkkachu Mar 11 '24 at 12:28