Cargo command not working under sudo

I am trying to install nightly rust on a new computer running ubuntu, and all the commands (rustc, cargo, rustup) are working, but only if I do not run them as root. For example, if I want to build a program without using sudo, it will say:

error: failed to open: /home/thiv/project/target/debug/.cargo-lock

Caused by:
  Permission denied (os error 13)

Naturally, I tried to use "sudo cargo build", but the terminal responds with:

sudo: cargo: command not found

How do I fix this?

Did you install rustc and cargo via rustup or via apt?

rustc and cargo installed by rustup aren't intended to be used with sudo, ever. Why are you using sudo?

1 Like

Cargo gets installed locally per user by rustup. For example my cargo executable is: /home/zicog/.cargo/bin/cargo

When you run as root/sudo then your home directory is /root and/or your environment is gone and of course nothing works.

But the question is why is your .cargo-lock not usable? Sounds like the lock is still held by another cargo instance.

Maybe that .cargo-lock is now owned by root from a previous sudo attempt?

2 Likes

Ah, It turns out that the file was locked because I pulled changes in the project from gitlab, which locks the files, so I unlocked them using chmod, and now I don't need root.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.