I have seen colleagues prefix (interactive) shell commands with env
, such as env KEY=value my_script
to invoke my_script
.
My question is: what's the point of using env
here? Why wouldn't you just write KEY=value my_script
?
I understand what env
does, and use cases such as #!/usr/bin/env python
make perfect sense. But, I do not understand why you would prefix env
to commands in an interactive shell.
There's probably no good reason why you'd have to use env
in an interactive command.
In a Bourne-derived shell (sh, ksh, bash, zsh), these two commands:
key=VALUE my_script
env key=VALUE my_script
are essentially identical.
The difference is that in the first command, key=Value
is part of the shell's syntax, not part of the command that's executed. env
is an actual command (it's typically not built into the shell). Because of that, there are contexts where you need to use env
, for example if you're running a command that invokes another command. For example, if you're using find
with the -exec
option:
find . -type f -exec some_command \;
then some_command
is invoked by find
, not by the shell, and a leading key=VALUE
won't be recognized. You can use env
to work around that.
That's a fairly unusual situation, though, and it doesn't apply to running a simple command.
Another possible reason is that the csh and tcsh shells (which are not derived from the Bourne shell) don't use the same syntax. Someone who's accustomed to using csh or tcsh interactively might use env key=Value my_script
out of habit.
Or someone might feel that using the env
command is more explicit and therefore clearer.
At worst, it's a harmless quirk. It does invoke an additional process and is probably slightly less efficient, but in an interactive command that doesn't really matter.
And as chepner's comment points out the env
command lets you set environment variables with names that aren't valid shell variable names (though that's rarely a good idea), and the -i
option lets you clear the existing environment before setting variables.
(As for the #!/usr/bin/env
hack, see this question and my answer for a discussion.)
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