josephj11

kdesudo() function for bash - updated 5-25-2019

Oct 16th, 2019
84
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function kdesudo () (
  2.   ## kdesudo replacement
  3.   ## Copyleft 08/28/2018 - Joseph Pollock - JPmicrosystems
  4.   ## Last modified 05/25/2019
  5.   ## Usage: kdesudo [-t "Dialog Title"] [-p "Dialog Prompt"] command and arguments
  6.  
  7.   ## Just like sudo, it only prompts if sudo permission has timed out
  8.   ## Won't work if your command is -t or -p
  9.   ## and the corresponding flag isn't specified - BUT SERIOUSLY?
  10.  
  11.   ## NOTE: use of () instead of {} puts function body in a subshell
  12.   ##       so all variables are local
  13.  
  14.   ## NOTE: Can fail on race condition between sudo test and sudo run
  15.  
  16.   ## NOTE: Does *not* handle embedded blanks in the command
  17.   ##       It does handle them in the arguments to the command
  18.  
  19.   ##source ~/bin/bash_trace  ## debug TRACE
  20.  
  21.   prompt=" "
  22.   while (( $# )) ## Process optional function arguments
  23.   do
  24.     case "$1" in
  25.       "-t")
  26.         shift
  27.         if [[ -n "$1" ]] ## Ignore empty string
  28.         then
  29.           kcmd=("${kcmd[@]}" "--title" "$1")
  30.           ##echo "kcmd [${kcmd[@]}]"  ## debug
  31.         fi
  32.         shift
  33.       ;;
  34.       "-p")
  35.         shift
  36.         [[ -n "$1" ]] && prompt="$1" ## Ignore empty string
  37.         shift
  38.       ;;
  39.       *) ## Stop looking for kdesudo args as soon as any other argument is present
  40.         break
  41.       ;;
  42.     esac
  43.   done
  44.  
  45.   if (( ! $# )) ## There has to be some command to run
  46.   then
  47.     return 2
  48.   fi
  49.  
  50.   args=("$@")
  51.   ##echo "args [${args[@]}]"  ## debug
  52.   sudo -n true &> /dev/null  ## Returns 0 if sudo runs without password
  53.   ##false  ## debug Returns 1 for testing when sudo hasn't timed out
  54.   if (( ! $? ))         ## if sudo is already activated - not timed out
  55.   then
  56.     sudo -- "${args[@]}"  ## then just run the command
  57.   else                  ## Otherwise display password dialog
  58.     kdialog --password "$prompt" "${kcmd[@]}" | sudo -S -- "${args[@]}"
  59.   fi
  60.  
  61.   rc=$?
  62.   [[ $rc == 141 ]] && rc=0 ## ignore a broken pipe
  63.   return $rc
  64. )
RAW Paste Data