1

I've made a custom command in bash and I placed it in ~/.local/bin which is a path loaded by the ~/.profile. When I run the command through a terminal without sudo it's fine, but when I try to run it with sudo the output is:

sudo: my_command: command not found

Could you tell me how I can accomplish that?

sourcejedi
  • 48,311
  • 17
  • 143
  • 296
  • `sudo $(type -P my_command)` – jordanm Apr 02 '19 at 19:59
  • Possibly related: [How to make `sudo` preserve $PATH?](https://unix.stackexchange.com/questions/83191/how-to-make-sudo-preserve-path) [command not found using sudo in script](https://unix.stackexchange.com/questions/292889/command-not-found-using-sudo-in-script) – fra-san Apr 02 '19 at 20:44

2 Answers2

1

Try sudo -E, this preserves your environment, may not work in all cases.
Seeing as you need an environment variable that is set by .profile also try sudo -i this performs a login, requiring you to also use -c my_command
If you still want to use sudo my_command without the any options check your /etc/sudoers file, and ensure the secure_path variable is set and contains the path that contains your command. This may require placing it somewhere generally available like /usr/local/bin

pacmanwa
  • 359
  • 4
  • 16
1

sudo has a PATH that is different than yours. sudo does not read ~/.profile.

Check it out:

$ sudo sh
# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# 

Compare the output you get to verify that ~/.local/bin is not included.

Accomplishing what you want to do is best done like this:

sudo ~/.local/bin/YourBashScript

Technically, you could also change sudo's PATH, but that's probably not your best move.

Seamus
  • 2,522
  • 1
  • 16
  • 31