Skip to content

Instantly share code, notes, and snippets.

@for2ando
Created July 25, 2020 11:27
Show Gist options
  • Save for2ando/4cb3c7f6eb46c9ce27862b0cdc32094d to your computer and use it in GitHub Desktop.
Save for2ando/4cb3c7f6eb46c9ce27862b0cdc32094d to your computer and use it in GitHub Desktop.
a simple sudo command for Windows with Cygwin.
#!/bin/sh
pname=$(basename "$0")
usage="$pname [-c|--console] Command [Argument ...]
$pname {-h|--help)
FEATURES
execute Command with Argument(s) on Windows's 'elevated' state.
OPTIONS
-c, --console
open another window and print the output of the elevated Command there.
-h, --help
print this help message.
EXAMPLES
sudo id
The result of 'id' is of elevated state.
sudo cat /etc/ssh_host_rsa_key >file
The 'file' is written with non-elevated permission.
sudo vi /etc/passwd
BUGS
sudo id | less
cat file | sudo id
These examples doesn't perform expected action.
Pipe cannot use with this sudo script.
sudo sh
Job control commands (such as Ctrl-C, Ctrl-Z, ...) are no effect in
the above eleveted 'sh'.
sudo less /etc/ssh_host_rsa_key
Above 'less' can't receive interactive command from a console.
THANKS TO
LHO
http://unavoidablereset.blog.fc2.com/blog-entry-15.html"
consolep=false
errp=false
while true; do
case "$1" in
-c|--console) consolep=true; shift;;
-h|--help) echo "$usage"; exit 0;;
-*) echo "$pname: $1: Unknown option.">&2; errp=true; shift;;
*) break;;
esac
done
$errp && exit 1
test $# -eq 0 && { echo "$usage">&2; exit 1; }
# If following trap isn't set, then this script stops by Ctrl-z
# while the elevated Command don't stop.
trap "" TSTP
STDIN=$(ls /proc/$$/fd/0 -l | awk '{print $11}')
STDOUT=$(ls /proc/$$/fd/1 -l | awk '{print $11}')
STDERR=$(ls /proc/$$/fd/2 -l | awk '{print $11}')
if $consolep; then
cygstart -a runas /usr/bin/mintty -h always "$*"
else
cygstart --hide -w -a runas sh -c "'exec <$STDIN >$STDOUT 2>$STDERR;$*'"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment