1

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 
2
  • 4
    Why do you need to run it with sudo? Do you want to do something like command -v ... to test if a command is available in the sudo environment?
    – muru
    CommentedApr 29, 2023 at 3:04
  • I added an example of the failure that I imagine that you may see (taken from an Alpine Linux system). Please revise this if it does not correctly reflect what it is you are doing.
    – Kusalananda
    CommentedApr 29, 2023 at 9:31

1 Answer 1

2

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.

3
  • To add to this, to verify whether a command is a shell builtin or an external command such as a binary in /usr/bin, use, in this case, type command.CommentedApr 29, 2023 at 9:36
  • 1
    @NasirRiley Note that type 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).
    – Kusalananda
    CommentedApr 29, 2023 at 9:52
  • I understand. I was only stating that for this case, in which it's known which one is wanted, 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

You must log in to answer this question.