Wednesday, September 8, 2010

running aliases and functions with sudo, and Blogger bashing

I don't remember where I got this like 3 years ago. Just thought I'd share it because it's very useful. Maybe it will be as useful for you as it is for me.

Blogger seems to always mess up my indentations. So it's not really good for python code. However, this is a bash function to wrap aliases and functions in sudo. I wish blogger wouldn't do that. But wait folks that's not all. It assists me in losing changes too. Gotta love that. If you see me switch over to posterous or not blog on here anymore, then you will know why. Not much incentive to use a system that screws with your text or text formating. hahaha, even Gov. Arnold has a posterous.

Better yet I will place code in a gist and keep ranting :) (I'll leave the below function declaration so you can see how ugly it looks)



sudo ()
{
local c o t parse

# Parse sudo args
OPTIND=1
while getopts xVhlLvkKsHPSb:p:c:a:u: t; do
if [ "$t" = x ]; then
parse=true
else
o="$o -$t"
[ "$OPTARG" ] && o="$o $OPTARG"
fi
done
shift $(( $OPTIND - 1 ))

# If no arguments are left, it's a simple call to sudo
if [ $# -ge 1 ]; then
c="$1";
shift;
case $(type -t "$c") in
"")
echo No such command "$c"
return 127
;;
alias)
c=$(type "$c"|sed "s/^.* to \`//;s/.$//")
;;
function)
c=$(type "$c"|sed 1d)";\"$c\""
;;
*)
c="\"$c\""
;;
esac
if [ -n "$parse" ]; then
# Quote the rest once, so it gets processed by bash.
# Done this way so variables can get expanded.
while [ -n "$1" ]; do
c="$c \"$1\""
shift
done
else
# Otherwise, quote the arguments. The echo gets an extra
# space to prevent echo from parsing arguments like -n
# Note the lovely interactions between " and ' ;-)
while [ -n "$1" ]; do
c="$c '$(echo " $1"|sed -e "s/^ //" -e "s/'/'\"'\"'/")'"
shift
done
fi
# Run the command with verbose options
echo Executing sudo $o -- bash -x -v -c "$c" >&2
command sudo $o bash -xvc "$c"
else
echo sudo $o >&2
command sudo $o
fi
}

No comments: