Issue
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.
Solution
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.)
Answered By - James Ko Answer Checked By - Gilberto Lyons (WPSolving Admin)