Search code examples
bashshellsu

Emulating sudo's behaviour with su


I'm trying to write a wrapper around su to make it more like sudo, so that su_wrapper foo bar baz == su -c "foo bar baz".

However, I'm not sure how to approach this problem. I came up with this:

su_wrapper ()
{
  su -c "$@"
}

However, in the above, only a single argument can be there; this fails with multiple arguments (as su sees them as its own arguments).

There's also another problem: since the argument is passed through the shell, I think I must explicitly specify the shell to avoid other problems. Perhaps what I want to do could be expressed in pseudo-bash(!) as su -c 'bash -c "$@"'.

So, how could I make it accept multiple arguments?


Solution

  • Use printf "%q" to escape the parameters so they can be used as string input to your function:

    su_wrapper() {
        su -s /bin/bash -c "$(printf "%q " "$@")"
    }
    

    Unlike $*, this works even when the parameters contain special characters and whitespace.