Sudo has no access to exported bash function

Hello.
I am running leap 15.1
sudo behavior may differ from other distrib.

I have a file with functions definition

....
function_1 {
echo "Hello world"

}
export -f function_1 

This file is sourced by both /etc/bash.bashrc.local and profile.local.

So the functions are accessible for every body.
for user root :

LC_ALL=C type -t function_1

return 'function'
for standard user

LC_ALL=C type -t function_1

return 'function'
for root user.

Now I write a script named test.sh which contain

#
# test.sh

#
# begin

function_1

# end

and put it in /tmp

Running as standard user :

:~>/tmp/test

I got

Hello world

Running as root user :

:#>/tmp/test

I got

Hello world

Now as standard user

sudo /tmp/test.sh

I got :

:~>sudo /tmp/test.sh
[sudo] password for root: 
/tmp/test.sh: line 1: function_1: command not found

How to give sudo access to exported function.

Now as root user

sudo /tmp/test.sh

I got :

:#>sudo /tmp/test.sh
[sudo] password for root: 
/tmp/test.sh: line 1: function_1: command not found

How to give sudo access to exported function.

sudo have access to environment variables which are exported , but not function.

Any help is welcome

These files are used on login. sudo bash is not a login.

Environment variables are external memory designed to be shared. Functions are part of a shell's internals and are not. For sudo bash to have a function, it will need to source that file.

#!/bin/bash

. /etc/bash.bashrc.local

function_1

sudo often blocks environment variables, by the way, to prevent people putting in strange values for EDITOR and the like and executing them with dangerous privileges.

1 Like

Hi,

You can preserve your current environment if you have been granted sufficient rights to do so with the -E switch or --preserve-env switch.

Regards

Gull04

My test show that does not work for function as Corona688 just said.

Thank you

--- Post updated at 18:06 ---

That mean that any script I run which need to be started with sudo needs to contains something like that :

#
# ~/test_001.sh
#

. /path/to/my_list_of_functions


#
# Code followed

#

But if the same script may be run by normal user, my functions will be sourced twice
One times by the login process via /etc/profile.local
One times by the code added on top of script.
What happens ?

Any comment is welcome.