Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash/WSL - How to run command as root?

>ubuntu1804.exe -c "echo $USER"
mpen  

That runs the command as me, how do I run it as root?

The help page doesn't even mention -c

>ubuntu1804.exe help
Launches or configures a Linux distribution.

Usage:
    <no args>
        Launches the user's default shell in the user's home directory.

    install [--root]
        Install the distribuiton and do not launch the shell when complete.
          --root
              Do not create a user account and leave the default user set to root.

    run <command line>
        Run the provided command line in the current working directory. If no
        command line is provided, the default shell is launched.

    config [setting [value]]
        Configure settings for this distribution.
        Settings:
          --default-user <username>
              Sets the default user to <username>. This must be an existing user.

    help
        Print usage information.
like image 277
mpen Avatar asked Jul 15 '26 03:07

mpen


2 Answers

Turns out there's another command simply called wsl that lets you run arbitrary commands as arbitrary users:

>wsl -u root -d Ubuntu-18.04 -- echo "I am g$USER"
I am groot

N.B. you need to use separate args (instead of a string) for this one.

-d is optional. You can change the default distro like

wslconfig.exe /l
wslconfig.exe /s Ubuntu-18.04
wslconfig.exe /l

wslconfig /l appears to be equivalent to wsl --list

like image 80
mpen Avatar answered Jul 18 '26 06:07

mpen


Often the root account is not active by default

Do this (it will prompt you to select the password for root):

sudo passwd root

and then you can login as root:

su root

After you have done with activities that request root privileges, re-login back as user:

su <username>
like image 45
dev-charodeyka Avatar answered Jul 18 '26 07:07

dev-charodeyka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!