How can I execute a bash function using sudo?

后端 未结 7 1281
终归单人心
终归单人心 2020-12-03 01:23

I tried exporting the function and then executing it with bash, but that doesn\'t work:

$ export -f my_func
$ sudo bash -c \'my_func\' 
bash: my_func: comma         


        
相关标签:
7条回答
  • 2020-12-03 02:05

    An alternative to calling your function with sudo is to just move the "sudo " calls inside your function. For example, I was wanting to set up a shortcut function in OS X for forwarding localhost to a particular port.

    function portforward() {
        echo "y" | sudo ipfw flush;
        sudo ipfw add 100 fwd 127.0.0.1,$1 tcp from any to any 80 in;
        echo "Forwarding localhost to port $1!";
    }
    

    The function hits sudo and asks for my password. (Then pipes "y" to a prompt for ipfw, not related to this question). After that, sudo is cached so the rest of the function executes without the need to enter a password.

    Essentially, this just runs like:

    portforward 8000
    Password:
    Forwarding localhost to port 8000!
    

    And fills my need because I only need to enter the password once and it's taken care of. Although it's a little ugly if you fail to enter the password the first time. Extra points for detecting whether the first sudo succeeded and exiting the function if not.

    0 讨论(0)
提交回复
热议问题