Command to launch an application or to show its window if already launched

I want to create a shorcut to 1) launch an application if it has not been launched yet, and 2) to show (or to bring to the front) the window of the app if it has already been launched.

For example: F10 for launching Stardict. I created a custom shorcut with the command "stardict" and the key F10, so each time I press F10, the system launch a new instance of Stardict, but this is not what I want.

Can anybody help please?

Thank you in advance.

UPDATE: In addition, I want to add something like: if the window is already shown, a press on the shortcut key (always the same) will minimize it to the system tray.

Many thanks to desgua for his complete solution below (answer section). By the way, before desgua posted his solution, I had found another solution, but not tested: http://ubuntuforums.org/showthread.php?t=1464311


To launch an application or to show its window if already launched or to minimize if it is focused

1) Install wmctrl: sudo apt-get install wmctrl

2) Install xdotool: sudo apt-get install xdotool

3) Make a script:

  • Make a file gedit ~/.focusshortcut
  • And paste this:
#!/bin/bash
#
# This script does this:
# launch an app if it isn't launched yet, 
# focus the app if it is launched but not focused,
# minimize the app if it is focused. 
#
# by desgua - 2012/04/29, last update: 2012/12/11

# Instructions
name=$(echo $0 | sed 's/.*\///')
if [ $# -ne 1 ]; then
echo "
This script does this:

# launch an app if it isn't launched yet, 
# focus the app if it is launched but not focused,
# minimize the app if it is focused. 

Usage: $name app

Example: 

$name gcalctool
"
exit 1

fi




# Let's check if the needed tools are instaled: 


tool1=$(which xdotool)
tool2=$(which wmctrl)

if [ -z $tool1 ]; then
    echo "Xdotool is needed, do you want to install it now? [Y/n]"
    read a 
    if [[ $a == "Y" || $a == "y" || $a = "" ]]; then
        sudo apt-get install xdotool
    else
        echo "Exiting then..."
        exit 1
    fi
fi

if [ -z $tool2 ]; then
    echo "Wmctrl is needed, do you want to install it now? [Y/n]"
    read a 
    if [[ $a == "Y" || $a == "y" || $a = "" ]]; then
        sudo apt-get install wmctrl
    else
        echo "Exiting then..."
        exit 1
    fi
fi


# Check if the app is running

pid=$(pidof $1)

# If it isn't launched, then launch

if [ -z $pid ]; then
    $1 
    exit 0
else  

# If it is launched then check if it is focused

foc=$(xdotool getactivewindow getwindowpid)

    if [[ $pid == $foc ]]; then

        # if it is focused, then minimize
        xdotool getactivewindow windowminimize
        exit 0

    else

        # if it isn't focused then get focus
        wmctrl -x -R $1
        exit 0

    fi
fi

exit 0

  • Make it executable: chmod +x ~/.focusshortcut

3) Make your shortcut point to /home/<user>/.focusshortcut app_to_show

4) Enjoy ;-)