Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Initial conditions : I have defined a function and export it:

myfunction () { echo OK ; }
export -f myfunction

I have a simple bash file : test.sh

#!/bin/bash
myfunction

Test OK with the current user : If I run :

bash test.sh

It works :)

Does not work with sudo : But if I run in sudo :

sudo bash test.sh

I have the error :

test.sh: ligne2: myfunction : commande introuvable

which means

test.sh: line2: myfunction : command not found

Question

Why my function does not work in sudo ? How it can work in sudo ?

Thank you very much :)

share|improve this question
    
Does it use your user files? If so, it requires the full path (because otherwise it defaults to /root not /home/username. So instead of referring to Pictures, refer to /home/username/Pictures. –  Tim Jul 6 at 18:56
    
Posting your script would be helpful... –  Tim Jul 6 at 19:04
    
This question was already asked on Superuser (superuser.com/questions/232231/…), StackOverflow, twice (stackoverflow.com/questions/5903247/preserve-sudo-environment, stackoverflow.com/questions/8633461/…), and Unix, 3 times. These are 6 of the first 7 results on Google when I search for sudo preserve environment variables. –  trysis Jul 7 at 2:32
    
In fact, this seems to be the only relevant SE site this question wasn't asked on (properly). It was even (sort of) asked on ServerFault. –  trysis Jul 7 at 4:20

1 Answer 1

For security reasons sudo throws away shell functions and most environment variables before running its child process.

You need to include the definition of myfunction into test.sh.

share|improve this answer
    
Is there any other way to share function or alias with sudo ? In my real situation, I have only 1 function myfunction and about 50 script test.sh –  sangorys Jul 6 at 20:31
    
Yes @sangorys, there is a switch you can use. I forget what it is at the moment, but when I remember (read: search for it), I will post it. –  trysis Jul 7 at 2:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.