open core »

Script to detect and run gksudo or kdesudo in Linux

If you are developing a Linux GUI application that requires root privileges, and you want it to be runnable in both KDE and Gnome desktop managers, this script solves the problem by trying to detect which of the commands are installed in the system and then runs your application with the available command:

#!/bin/bash

# searches for the presence of a given command
findCmd () {
     temp=1
     auxIFS="$IFS"
     IFS=:
     for d in $PATH; do
          case $d in '') d=. ;; esac
          if [ -f "$d/$1" ] && [ -x "$d/$1" ]; then
               temp=1
               break
          fi
     done
     IFS="$auxIFS"

     return $temp
}

# now let's run the found command
_sudo =
if findCmd gksudo; then
     _sudo=gksudo
elif findCmd kdesudo; then
    _sudo=kdesudo
else
     _sudo=sudo
fi

$_sudo yourApp   # change "yourApp" to you app's command

This way you can provide support for both desktop managers running privileged applications. There are other ways to do this, but this is a quick and dirty way.

Update: As João Craveiro mentioned in a comment, this might not work when both desktop managers are installed.