How to execute the Bash command command
using sudo
in order to run it as root?
Using sudo command
fails:
$ sudo command ls sudo: command: command not found
The sudo
command is able to run an external command as another user. It can not be used to directly execute commands that are built into the shell. This also applies to the doas
command on systems that uses it in place of sudo
.
On some systems, the command
command is available as an external command (/usr/bin/command
on macOS, for example). On these systems, there would be no issue in using sudo command ...
, other than the fact that it's not the shell's internal command
command that is being executed, which could matter depending on what it is you are attempting to do.
On other systems, where command
is only available as a command built into a shell, you may have to use sudo
on the particular shell and in that way indirectly call that shell's built-in command
:
sudo bash -c 'command ...'
Again, whether this does what you want depends on what it is you want to achieve.
/usr/bin
, use, in this case, type command
.CommentedApr 29, 2023 at 9:36type command
(or command -V command
) would say command is a shell builtin
in shells where the command is a built-in, even though there is an external variant of the command available. You would have to get the shell to ignore the command in order to test whether there was an external variant of the command available. In Bash, you could use (enable -n command; type command)
.type command
will identify it as a shell builtin. If that wasn't the case, then your method would apply. It's good to have this information anyway because both the shell builtin and /usr/bin/command
operate very similarly.CommentedApr 29, 2023 at 11:34
command -v ...
to test if a command is available in the sudo environment?