如何使用命令行获取正在运行的应用程序列表?

Modified on: Sat, 09 Jun 2018 03:36:53 +0800

我想使用命令行列出仅运行的应用程序:Firefox,gedit,Nautilus等。

注意:我不想列出所有正在运行的进程,只列出正在运行的应用程序(比如手动启动的GUI)。

作者:muru,Pandya

最佳答案

wmctrlxprop的组合提供了许多可能性。

示例1:

running_gui_apps() {

    # loop through all open windows (ids)
    for win_id in $( wmctrl -l | cut -d' ' -f1 ); do 

        # test if window is a normal window
        if  $( xprop -id $win_id _NET_WM_WINDOW_TYPE | grep -q _NET_WM_WINDOW_TYPE_NORMAL ) ; then 

            echo "$( xprop -id $win_id WM_CLASS | cut -d" " -f4- )"", window id: $win_id"

        fi

    done
}

在这种情况下,输出看起来像这样:

"Firefox", window id: 0x032000a9
"Gnome-terminal", window id: 0x03a0000c
"Thunar", window id: 0x03600004
"Geany", window id: 0x03c00003
"Thunar", window id: 0x0360223e
"Mousepad", window id: 0x02c00003
"Mousepad", window id: 0x02c00248
"Xfce4-terminal", window id: 0x03e00004

示例2:

running_gui_apps() {
    applications=()

    # loop through all open windows (ids)
    for win_id in $( wmctrl -l | cut -d' ' -f1 ); do 

        # test if window is a normal window
        if  $( xprop -id $win_id _NET_WM_WINDOW_TYPE | grep -q _NET_WM_WINDOW_TYPE_NORMAL ) ; then 

            # filter application name and remove double-quote at beginning and end
            appname=$( xprop -id $win_id WM_CLASS | cut -d" " -f4 )
            appname=${appname#?}
            appname=${appname%?}

            # add to result list
            applications+=( "$appname" ) 

        fi

    done

    # sort result list and remove duplicates  
    readarray -t applications < <(printf '%s\0' "${applications[@]}" | sort -z | xargs -0n1 | uniq)

    printf -- '%s\n' "${applications[@]}" 
}

输出示例:

Firefox Geany Gnome-terminal Mousepad Thunar Xfce4-terminal

您可以将该功能添加到~/.bashrc或从脚本文件中运行。

作者:,TuKsn

相关问答

添加新评论