2

So I'm sure this is written somewhere, and I'm just wording my searches wrong, but I haven't been able to find it.

I write shell scripts. Many of those scripts require superuser permissions. Rather than putting the sudo command inside the script, I want to invoke the entire script from the start with sudo.

So instead of:

#!/bin/bash
# Sample Script 1

sudo mkdir /usr/tempDir

It would be:

#!/bin/bash
# Sample Script 2

mkdir /usr/tempDir

And I would just invoke it like this: sudo ./sampleScript.sh

My problem is that when I write a script, I simlink it to my bin, so I don't need to worry about the path to the script when I execute it.

If I have the file simlinked to my bin, and I run it as just: sampleScript.sh, it is recognized (and will fail). However, if I do: sudo sampleScript.sh, I get a "sudo: sampleScript.sh: command not found" message.

This happens if it's in both /home/myName/bin and /usr/local/bin.

I know there has to be a trick to making this work that I'm missing. And I also know I'm probably just not wording my google searches properly. Just looking for some guidance to figure this part out.

Thanks.

craigmiller160
  • 5,751
  • 9
  • 41
  • 75
  • Have you tried `sudo sampleScript.sh` without the `./`? If that doesn't work, maybe try `sudo env "PATH=$PATH" sampleScript.sh`, because maybe sudo's own shell doesn't have that script's directory in its $PATH . – Dmiters Apr 18 '16 at 22:13
  • 1
    See http://unix.stackexchange.com/questions/83191/how-to-make-sudo-preserve-path – malbarbo Apr 18 '16 at 22:16
  • If my answer helped can you accept it please. – Harry Apr 20 '16 at 02:25

1 Answers1

3

When you call sudo the PATH changes ie it's not using yours. Look here

sudo changes PATH - why?

It does this because it's now running as root, not as your user.

Community
  • 1
  • 1
Harry
  • 11,298
  • 1
  • 29
  • 43