Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have a bash function defined in a global bashrc, which requires root privileges to work. How can I run it with sudo, e.g. sudo myfunction. By default it gives an error:

sudo: myfunction: command not found

share|improve this question
2  
Never tried, but this blog post seems to handle it: w00tbl0g.blogspot.com/2007/05/… –  Grizly Sep 3 '10 at 12:16
    
the installation of the above script require 'set alias sudo=sudowrap' which is not recommendable imho. Please see my answer for a solution which doesn't require anything to work. –  Luca Borrione Sep 2 '12 at 10:24

6 Answers 6

up vote 1 down vote accepted

Luca kindly pointed me to this question, here's my approach: Expand the function/alias before the call to sudo and pass it in its entirety to sudo, no temp files needed.

Explained here on my blog. There's lots of quote handling :-)

The one disadvantage to this approach is that it only expands the function you're calling, not any extra functions you're referencing from there. Kyle's approach probably handles that better if you're referencing functions that are loaded in your bashrc (provided it gets executed on the bash -c call).

share|improve this answer

Maybe you can do:

function meh() {
    sudo -v
    sudo cat /etc/shadow
}

This should work and saves you from typing sudo on the commandline.

share|improve this answer
    
Depending on your system... this will prompt you for every call of the sudo command to enter the password... or prompt you once & cache it. It would be better to detect if you're running as root, and if not... call the bash script again with sudo once. –  TheCompWiz Sep 3 '10 at 14:00
    
I have yet to encounter a system that does not cache the sudo password: the default for timestamp_timeout is 5. If you set it to 0, you are always asked for a password, but that would be a custom setting. –  wzzrd Sep 3 '10 at 14:36

I would execute a new shell by having sudo execute the shell itself, then the function will run with root privileges. For example something like:

vim myFunction
#The following three lines go in myFunction file
function mywho {
    sudo whoami
}

sudo bash -c '. /home/kbrandt/myFunction; mywho'
root

You could even then go to make an alias for the sudo bash line as well.

share|improve this answer

You can export your function to make it available to a bash -c subshell or scripts that you want to use it in.

your_function () { echo 'Hello, World'; }
export -f your_function
bash -c 'your_function'

Edit

This works for direct subshells, but apparently sudo doesn't forward functions (only variables). Even using various combinations of setenv, env_keep and negating env_reset don't seem to help.

Edit 2

However, it appears that su does support exported functions.

your_function () { echo 'Hello, World'; }
export -f your_function
su -c 'your_function'
share|improve this answer
2  
+1 , I would say this is the correct answer. –  Kyle Brandt Sep 6 '10 at 17:52
1  
whether this method works ?? In my case it is not. –  pradeepchhetri Mar 26 '12 at 12:04
    
@pradeepchhetri You may want to give more information, such as what you are precisely trying, which shell you use, and which OS you use. –  Legolas Mar 26 '12 at 13:23
    
@Legolas: I am trying the same thing script wrote in the above script. I am getting the error bash: your_function: command not found. I am using Ubuntu 11.04 and bash shell. –  pradeepchhetri Mar 26 '12 at 13:57
    
@pradeepchhetri what if you use sudo -E bash -c 'your_function'? –  Legolas Mar 26 '12 at 14:33
#!/bin/bash

function smth() {
    echo "{{"
    whoami
    echo "}}"
}

if [ $(whoami) != "root" ]; then
    whoami
    echo "i'm not root"
    sudo $0
else
    smth
fi
share|improve this answer

As pointed out by Legolas in the comments of the answer of Dennis Williamson you should read the answer of bmargulies on a similar question posted on stackoverflow.

Starting from that I wrote a function to cover this issue, which basically realizes the idea of bmargulies.

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# EXESUDO
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
#
# Purpose:
# -------------------------------------------------------------------- #
# Execute a function with sudo
#
# Params:
# -------------------------------------------------------------------- #
# $1:   string: name of the function to be executed with sudo
#
# Usage:
# -------------------------------------------------------------------- #
# exesudo "funcname" followed by any param
#
# -------------------------------------------------------------------- #
# Created 01 September 2012              Last Modified 02 September 2012

function exesudo ()
{
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
    #
    # LOCAL VARIABLES:
    #
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

    #
    # I use underscores to remember it's been passed
    local _funcname_="$1"

    local params=( "$@" )               ## array containing all params passed here
    local tmpfile="/dev/shm/$RANDOM"    ## temporary file
    local filecontent                   ## content of the temporary file
    local regex                         ## regular expression
    local func                          ## function source


    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
    #
    # MAIN CODE:
    #
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

    #
    # WORKING ON PARAMS:
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #
    # Shift the first param (which is the name of the function)
    unset params[0]              ## remove first element
    # params=( "${params[@]}" )     ## repack array


    #
    # WORKING ON THE TEMPORARY FILE:
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    content="#!/bin/bash\n\n"

    #
    # Write the params array
    content="${content}params=(\n"

    regex="\s+"
    for param in "${params[@]}"
    do
        if [[ "$param" =~ $regex ]]
            then
                content="${content}\t\"${param}\"\n"
            else
                content="${content}\t${param}\n"
        fi
    done

    content="$content)\n"
    echo -e "$content" > "$tmpfile"

    #
    # Append the function source
    echo "#$( type "$_funcname_" )" >> "$tmpfile"

    #
    # Append the call to the function
    echo -e "\n$_funcname_ \"\${params[@]}\"\n" >> "$tmpfile"


    #
    # DONE: EXECUTE THE TEMPORARY FILE WITH SUDO
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    sudo bash "$tmpfile"
    rm "$tmpfile"
}



Example of usage:
running the following snippet

#!/bin/bash

function exesudo ()
{
    # copy here the previous exesudo function !!!
}

test_it_out ()
{
    local params=( "$@" )
    echo "Hello "$( whoami )"!"
    echo "You passed the following params:"
    printf "%s\n" "${params[@]}" ## print array
}

echo "1: calling without sudo"
test_it_out "first" "second"

echo ""
echo "2. calling with sudo"
exesudo test_it_out -n "john done" -s "done"

exit



Will output

  1. calling without sudo
    Hello yourname!
    You passed the following params:
    first
    second

  2. calling with sudo
    Hello root!
    You passed the following params:
    -n
    john done
    -s
    foo



If you need to use this in a shell calling a function which is defined in your bashrc, as you asked, then you have to put the previous exesudo function on the same bashrc file as well, like the following:

function yourfunc ()
{
echo "Hello "$( whoami )"!"
}
export -f yourfunc

function exesudo ()
{
   # copy here
}
export -f exesudo



Then you have to logout and login again or use

source ~/.bashrc



Finally you can use exesudo as follow:

$ yourfunc
Hello yourname!

$ exesudo yourfunc
Hello root!
share|improve this answer

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.