what is bash command `command` used for and what is it when it appears in shell script
when I was writing a shell script, I happen to know command
is a reserved word. Then I noticed command
is also a bash command.
-
command ls
gives the same result asls
. -
command ls | grep xxx
gives the same result as without it.
Then I wonder what is it used for when it is a bash command. And what is it used for when it is in shell script. Thanks!
Solution 1:
command foo
will run the foo
command even if there is a foo
shell function defined. This behavior is required by POSIX.
It allows you to call the foo
command inside the foo
function. Without command foo
the function (when invoked) would call itself and create a circular reference.
Well, sometimes you can call the foo
executable by its full path to suppress the shell function lookup (cumbersome and not portable, still some kind of workaround), but in some cases you can't. E.g. in this answer of mine (near the end) I redefine cd
and command cd
is a must, because even if there is a cd
executable which full path I could use, it wouldn't change the directory. Using command
is the right way to deal with this.
Also note command foo
will not trigger a foo
alias (if any). You used ls
as an example. At least few common Linux distros alias ls
to ls --color=auto
by default. In this case ls
and command ls
may give different results (i.e. colored or not). POSIX (or any other) definition of command
doesn't need to mention aliases because bar foo
doesn't trigger foo
alias (if any) in the first place (with few possible exceptions regarding bar
, but command
is not one of them).
Whether you use command foo
in an interactive shell session or in a shell script may matter to foo
, but not to the command
builtin itself.