5

I'm writing a cross-platform shell script that's supposed to work on Unix, Cygwin, and msys. In my shell script I need to perform actions with elevated privileges. On Unix you would do this via sudo, and on Cygwin via something like cygstart --action=runas. What's the equivalent for msys?

All my Googling so far has only turned up this, which isn't practical from a shell script since you have to interact with the GUI.

Community
  • 1
  • 1
James Ko
  • 32,215
  • 30
  • 128
  • 239
  • What is the script you are trying to run? Keep in my mind. Its not a unix shell, it just emulates one. You probably would need to start msysgit with an elevated privilege. – deostroll Dec 28 '15 at 02:34
  • @deostroll The commands I am trying to run are: `mkdir -p`, `tee`, and `chmod` ([source code for script](https://github.com/jamesqo/sinister/blob/master/sinister#L116-L119)). – James Ko Dec 28 '15 at 02:36
  • This is not a shell problem. Not only is `sudo` an external command, it is not even defined by [POSIX](http://pubs.opengroup.org/onlinepubs/009696699/utilities/contents.html), and is certainly not available by default on many Unix or Unix-like systems, including many Linux distros (e.g. Arch). – 4ae1e1 Dec 28 '15 at 02:54

2 Answers2

2

Elevate does a decent job at this, though it's not entirely sudo-equivalent.

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221
1

I think I may have found a solution using PowerShell:

escape()
{
    RESULT="$1"
    RESULT="${RESULT/\'/\\\'\'}" # replace ' with \''
    RESULT="${RESULT/\"/\\\\\\\"}" # replace " with \\\"
    echo "''$RESULT''" # PowerShell uses '' to escape '
}

sudo()
{
    ESCAPED=()
    for ARG in "$@"
    do
        ESCAPED+=($(escape "$ARG"))
    done

    SHELL_PATH=$(cygpath -w $SHELL)
    PS_COMMAND="[Console]::In.ReadToEnd() | Start-Process '$SHELL_PATH' '-c -- \"${ESCAPED[*]}\"' -Verb RunAs"
    cat /dev/stdin | powershell -NoProfile -ExecutionPolicy Bypass "$PS_COMMAND"
}

Definitely a bit Extremely hackish, but it's better than nothing. (Or Batch files, for that matter.)

James Ko
  • 32,215
  • 30
  • 128
  • 239