$()
is command substitution. It executes the command inside the parentheses and returns the output of that command.
It's often used to get the output of a program into a variable. e.g.
$ month=$(date +%m)
$ echo $month
02
or to use the output of one program as args for another, e.g.
$ printf '%s\n' $(date +%B)
February
(ok, yeah, printf
is a contrived example because just running date +%B
produces the same output...but it does demonstrate how it works).
The command inside the parentheses may be as simple or as complex as you need, from a single program to a long pipeline of commands. e.g. I often use commands like the following to remove old kernel packages from my Debian system:
apt-get purge $(dlocate -k | grep '6\.0\.0-[245]')
BTW, you may also see scripts using backticks (`) for this. This is an old, obsolete form of command substitution, supported for legacy reasons but shouldn't be used in new scripts.
When used with eval
, it causes your shell to execute the output. In this case, running /opt/homebrew/bin/brew shellenv
returns a bunch of text like var=value
and eval
runs them in your current shell, thus setting those variables to the required values.
From help eval
in bash:
eval
: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
Try running /opt/homebrew/bin/brew shellenv
by itself to see what output it produces.
Thanks for help!
– Osbridge Feb 17 '23 at 02:11brew shellenv
not giving any output at all under some circumstances is explained bybrew help shellenv
(mentioned in a recent answer here: Command output evaluation not working in Bash script). – Kusalananda Feb 17 '23 at 07:21