简体   繁体   中英

How do I execute the arguments to a bash function as root using the su command?

I'm writing a script wherein I have a function that runs commands as root. This is so that it can use either sudo, doas, or su depending on what the user has installed. The function looks something like this:

as_root() {
    # $SU_CMD contains either sudo, doas --, or nothing
    if [[ -n $SU_CMD ]]; then
        $SU_CMD $@
    else
        su root -- $@
    fi
}

This does not work if neither sudo nor doas are available. Rather than executing the command as root, su root -- <command> writes /usr/bin/<command>: /usr/bin/<command>: cannot execute binary file to the terminal. I also tried su -c "$@" among other combinations, but no dice.

How would I go about executing the arguments to a bash function as root using su?

You have three commands you might want to run. Note that -- is recommended in all three cases.

  1. sudo -- "$@"
  2. doas -- "$@"
  3. su root -- "$@"

Since the name of the function implies that you always want su root (rather than su foo or some other user), there's no point in requiring root be included in SU_CMD . As such, you can simply write

as_root () {
  case $SU_CMD in
    sudo) sudo -- "$@" ;;
    doas) doas -- "$@" ;;
    su) su root -- -c "$*" ;;
    *) printf 'Invalid choice: %s\n' "$SU_CMD" >&2 ;;
  esac
}

(This could be refactored, but that hardly seems worth the effort, given the simplicity of the function.)

Use a single dash instead of two or better yet -l to avoid confusion:

as_root() {
    if [[ -n $SU_CMD ]]; then
        $SU_CMD "$@";
    else
        su root -l -c "$@";
    fi
}

morbeo@pc:~$ as_root whoami
Password:
root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM