웹사이트 검색

kdialog를 사용하여 Linux 셸 스크립트에 간단한 GUI 추가


쉘 스크립트는 매우 유용한 것입니다. 이를 통해 더 어려운 명령을 많은 플래그로 대체하는 쉬운 명령을 생성하고 cron 작업에서 실행할 많은 복잡한 명령을 일괄 처리하는 것과 같은 기본적인 작업을 수행할 수 있습니다. 자주 사용하는 터미널에서 신속하게 실행할 수 있기 때문에 훌륭하지만 경우에 따라 플래그 또는 옵션의 특정 조합을 기억해야 합니다. 이러한 상황에 처한 경우 몇 가지 간단한 GUI 대화 상자를 추가하여 당면한 작업을 빠르게 진행할 수 있습니다.

이 자습서를 사용하려면 다음이 필요합니다.

  • Unix와 같은 셸에 대한 액세스(bash를 염두에 두고 작성됨).\n\n
  • macOS 및 *nix OS(예: Linux)는 이것 또는 이와 유사한 것과 함께 제공되어야 합니다.\n
  • Windows에서는 CygWin 환경을 설치하거나 최신 버전의 Windows 10에서는 "Linux용 Windows 하위 시스템"을 사용할 수 있습니다.\n
  • KDE 데스크탑 환경의 기본 라이브러리입니다. 특히 다른 DE가 이미 설치되어 있는 경우 전체가 필요하지 않습니다.\n

kdialog 설치는 KDE가 아닌 데스크탑 환경에서 시작했고 컴퓨터에 다른 KDE 응용 프로그램이 없는 경우에만 필요합니다. Ubuntu의 kde-baseapps-bin 패키지의 일부이며, 이는 Kubuntu에 기본적으로 설치됨을 의미합니다. 다른 파생 상품에서는 터미널에서 다음 명령으로 설치할 수 있습니다.

터미널에서 kdialog를 설치합니다.

sudo apt-get install kde-baseapps-bin

다른 KDE 라이브러리와 패키지가 함께 설치되기 때문에 상당한 규모의 설치가 될 것입니다. 하지만 하드 드라이브 공간은 저렴합니다.

스크립트는 (일반적으로) 자동으로 작업을 수행하도록 되어 있으므로 다음 상황에서만 이 대화 상자를 표시하면 됩니다.

  • 사용자로부터 어떤 종류의 입력을 캡처해야 하는 경우 또는\n
  • 사용자에게 눈에 띄는 방식으로 일종의 피드백을 표시하려는 경우(즉, 명령줄에서 일부 텍스트가 뱉어지는 것이 아님).\n

[drush를 사용하여 Drupal 사이트 백업] 명령을 사용하는 예를 들어 보겠습니다. 물론, 당신은 신진 인터넷 기업가이기 때문에 Drupal 사이트가 하나만 있는 것은 아닙니다—? 당신은 세 가지가 있습니다. 모든 사이트를 백업하려는 경우 별도의 명령을 실행하지 않아도 되지만 동시에 하나의 스냅샷을 찍으려는 경우 긴 경로를 기억할 필요도 없습니다. 몇 가지 대화 상자를 사용하여 다음을 수행할 수 있습니다.

  • 사용자에게 백업할 수 있는 사이트 목록을 제시하고 선택할 수 있도록 합니다.\n
  • 성공 또는 실패 여부에 관계없이 결과를 확인하는 메시지를 사용자에게 보여줍니다.\n

kDialog는 대화 상자 유형, 유형에 필요할 수 있는 모든 매개 변수 및 대화 제목과 같은 기타 옵션과 함께 명령줄에서 호출하여 작동합니다.

다음과 같이 필요에 따라 선택할 수 있는 다양한 대화 유형이 있습니다.

kDialog Types
Dialog TypeSample ImageDescription

Information Message Boxes

Displays a box with an "OK" button to close, providing a text message and either a "non-critical" information, warning, or error icon.

Passive Pop-up

This displays a message that will disappear within a few seconds, i.e. it doesn’t require the user to close or dismiss it.

Yes/No Message Box

Like the "Information Message Boxes," this displays a dialog with an information/warning/error icon that will also provide the user’s selection of "Yes" or "No."

Input Dialog Boxes

This provides a single box into which the user can type some text.

File Display Boxes

This will display the contents of a (plain text) file within a dialog box.

Menu and Selection Dialog Boxes

This provides a dialog with a list of items, allowing the user to make one or more selections:

  • The Menu and Radiolist Dialogs allow selection of one option.

  • The Checklist Dialog allows selection of one, multiple, or all options.

  • The Combobox Dialog allows the selection of one option using a drop-down menu.

File Selection Dialog Boxes

The user can select part of the filesystem, including:

  • Select existing files, with the ability to filter by name or filetype

  • Enter a new of a new file to be saved/updated

  • Directories

Progress Dialogs

The user can combine kDialog with the dcop command to create a dialog that updates the user on the progress of an operation.

위의 옵션을 살펴보면 그 중 두 가지가 잠재력이 있는 것으로 뛰어납니다.

  • "체크리스트 대화상자"를 사용하면 백업할 사이트 중 하나 또는 전체를 선택할 수 있습니다.\n
  • "정보 메시지 상자"는 각각의 성공 여부를 표시하는 데 사용할 수 있습니다.\n

이러한 옵션이 주어지면 스크립트가 다음과 같이 보이는 것을 상상할 수 있습니다.

SITE1 is located HERE (make these full paths, not relative paths)
SITE2 is located THERE
SITE3 is located IN ANOTHER PLACE

display a kDialog with SITE1, SITE2, and SITE3 as options
    and tell me which one(s) the user picks

for each one the user picked:
    run +drush ard+ on that site, and
    record whether it was successful or not.

display another +kDialog+ with each of those results.

이를 염두에 두고 바로 들어가 보겠습니다.

가장 먼저 해야 할 일은 각 사이트가 선택되었을 때 적용할 drush 명령을 조합하는 것입니다. 모든 사이트가 서로 다른 디렉토리의 동일한 웹 호스트에 있지만 공통 "백업" 디렉토리에 백업을 저장하려고 한다고 가정합니다. 다음을 사용할 수 있습니다.

cd SITE
drush ard --destination=/home/user/backup/SITENAME.tar.gz

따라서 for 루프에 대한 지식을 사용하여 이 스크립트를 다음과 같이 만들 수 있습니다.

#! /bin/bash

// Note: create variables to hold paths to all the sites
PERSONALSITE='/home/www/mypersonalsite/'
BUSINESSSITE='/home/www/mybusinesssite/'
HOBBYSITE='/home/www/myhobbysite/'

// Note: create variable to hold path to the destination
DESTINATION='/home/user/backup'

// Note: display a dialog asking the user to select which sites to back-up
CHOICES=$(kdialog --checklist "Select sites to back-up:" 1 "Personal site" off 2 "Business Site" off 3 "Hobby site" off)

// Note: log a success/failure message for each of the choices returned from dialog
for each in $CHOICES
do
    case {
        1)
            cd $PERSONALSITE
            drush ard --destination=$DESTINATION/mypersonalsite.tar.gz
            if [$?=="0"]
            then
                RESULTS += "Personal site backup: Succeeded\n"
            else
                RESULTS += "Personal site backup: Failed\n"
            fi
        2)
            cd $BUSINESSSITE
            drush ard --destination=$DESTINATION/mybusinesssite.tar.gz
            if [$?=="0"]
            then
                RESULTS += "Business site backup: Succeeded\n"
            else
                RESULTS += "Business site backup: Failed\n"
            fi
        3)
            cd $HOBBYSITE
            drush ard --destination=$DESTINATION/myhobbysite.tar.gz
            if [$?=="0"]
            then
                RESULTS += "Hobby site backup: Succeeded\n"
            else
                RESULTS += "Hobby site backup: Failed\n"
            fi
    esac

// NOTE: display a dialog with the results of all the backup operations.
kdialog --msgbox $RESULTS

이것을 저장하고 Bash 시리즈의 첫 번째 기사에 설명된 대로 실행할 수 있게 만들면 단일 명령을 실행할 수 있고 사용하기 쉬운 대화 상자를 통해 사이트를 선택한 다음 멋진 창 보고를 볼 수 있습니다. 모든 것이 어떻게 돌아가는지.

이 스크립트는 확실히 몇 가지 방법으로 최적화될 수 있지만 kdialog를 사용하여 일부 사용자 입력을 수집하고 스크립트 내에서 단일 프로그램을 실행하여 일부 결과를 표시하는 방법을 보여줍니다.