Menu

Examples

Anonymous

Introduction

Here is set of examples demonstrate how to use yad in shell scripts.

Logout dialog

Show logout dialog.

Additional software:

code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! /bin/bash

action=$(yad --width 300 --entry --title "System Logout" \
    --image=gnome-shutdown \
    --button="Switch User:2" \
    --button="gtk-ok:0" --button="gtk-close:1" \
    --text "Choose action:" \
    --entry-text \
    "Power Off" "Reboot" "Suspend" "Logout")
ret=$?

[[ $ret -eq 1 ]] && exit 0

if [[ $ret -eq 2 ]]; then
    gdmflexiserver --startnew &
    exit 0
fi

case $action in
    Power*) cmd="sudo /sbin/poweroff" ;;
    Reboot*) cmd="sudo /sbin/reboot" ;;
    Suspend*) cmd="sudo /bin/sh -c 'echo disk > /sys/power/state'" ;;
    Logout*) 
    case $(wmctrl -m | grep Name) in
        *Openbox) cmd="openbox --exit" ;;
        *FVWM) cmd="FvwmCommand Quit" ;;
            *Metacity) cmd="gnome-save-session --kill" ;; 
        *) exit 1 ;;
    esac
    ;;
    *) exit 1 ;;    
esac

eval exec $cmd

Run dialog

Run dialog with history, URI recognition and run-in-xterm functions

Additional software:

  • xterm
  • perl

code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#! /bin/bash

XTERM="xterm"

# create history file
mkdir -p ${XDG_CACHE_HOME:-$HOME/.cache}/
HISTFILE=${XDG_CACHE_HOME:-$HOME/.cache}/ix-run.history
touch $HISTFILE

# create and run dialog
TITLE="Run command"
TEXT="\nEnter command to execute:\n"
rcmd=$('yad --width=500 --center --window-icon="gtk-execute" --name="${0##*/}" --title="$TITLE" --text="$TEXT" --image="gtk-execute" --entry --editable --rest="$HISTFILE")

[[ -z "$rcmd" ]] && exit 0

# run command
case $rcmd in
    http://*|https://*|ftp://*)
    xdg-open $rcmd &
    ;;
    mailto://*)
    xdg-email $rcmd &
    ;;
    man://*)
    eval $XTERM -e "man ${rcmd#man://}" &
    ;;
    telnet*|ssh*)
    eval $XTERM -e "$rcmd" &
    ;;
    *)
    eval $rcmd &
    ;;
esac

# add command to history
grep -q -F "$rcmd" $HISTFILE || sed -i "1 i $rcmd" $HISTFILE

exit 0

Autostart editor

Edit content of $HOME/.config/autostart.

code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! /bin/bash

config_dir=${XDG_CONFIG_HOME:-$HOME/.config}
results=$(mktemp --tmpdir autostart.XXXXXXXXXX)

for f in $config_dir/autostart/*.desktop; do
    grep -m 1 -e '^[[:blank:]]*Exec' $f | cut -d = -f 2
    grep -m 1 -e '^[[:blank:]]*Name' $f | cut -d = -f 2
    grep -m 1 -e '^[[:blank:]]*Comment' $f | cut -d = -f 2
done | yad --width=500 --height=300 --title="Autostart editor" --image="gtk-execute" \
           --text="Add/remove autostart items" --list --editable --print-all \
           --multiple --column="Command" --column="Name" --column="Description" > $results

if [[ ${PIPESTATUS[1]} -eq 0 ]]; then
    rm -f $config_dir/autostart/*.desktop
    i=0
    cat $results | while read line; do
        eval $(echo $line | awk -F'|' '{printf "export NAME=\"%s\" COMMENT=\"%s\" COMMAND=\"%s\"", $2, $3, $1}')
        cat > $config_dir/autostart/$i$NAME.desktop << EOF
[Desktop Entry]
Encoding=UTF-8
Name=$NAME
Comment=$COMMENT
Exec=$COMMAND
StartupNotify=true
Terminal=false
EOF
    $((i++))
    done
    unset NAME COMMENT COMMAND
fi

rm -f $results
exit 0

Graphical frontend for su(1)

Run program as a different user (root by default). Ask password if needed

Additional software:

code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#! /bin/bash

# some defaults
user="root"
suargs="-p"
force="no"

# parse commandline   
if [[ $# -eq 0 ]]; then
    echo "Usage: ${0##*/} [-f] [-u user] [--] "
    exit 1
fi

OPTIND=1
while getopts u: opt; do
    case "$opt" in
        f) force="yes" ;;
        u) user="$OPTARG" ;;
    esac
done
shift $((OPTIND - 1))

cmd="$*"

if [[ $force != "no" ]]; then
    # check for sudo
    sudo_check=$(sudo -H -S -- echo SUDO_OK 2>&1 &)
    if [[ $sudo_check == "SUDO_OK" ]]; then
        eval sudo $cmd
        exit $?
    fi
fi

# get password
pass=$(yad --class="GSu" \
    --title="Password" \
    --text="Enter password for user <b>$user</b>:" \
    --image="dialog-password" \
    --entry --hide-text)
[[ -z "$pass" ]] && exit 1

# grant access to xserver for specified user
xhost +${user}@ &> /dev/null

# run command
fifo_in="$(mktemp -u --tmpdir gsu.empty.in.XXXXXXXXX)"
fifo_out="$(mktemp -u --tmpdir gsu.empty.out.XXXXXXXXX)"

LC_MESSAGES=C empty -f -i $fifo_in -o $fifo_out su $suargs $user -c "$cmd"
[[ $? -eq 0 ]] && empty -w -i $fifo_out -o $fifo_in "word:" "$pass\n"

exit $?

Discussion

<< < 1 2 3 (Page 3 of 3)
  • Anonymous

    Anonymous - 2012-12-05

    Originally posted by: peterpas...@gmail.com

    Is there (or could there be) any provision for which element of the dialog has focus?

    This was my main gripe with Zenity, that (for instance in a question dialog) you could not set which of the 2 buttons was the default selected (it was OK and I needed No as default).

     
  • Anonymous

    Anonymous - 2013-01-15

    Originally posted by: georgian...@gmail.com

    Hi. It is possible that the source of a combo box to be a file?

     
  • Anonymous

    Anonymous - 2013-01-15

    Originally posted by: ananasik

    yes. use --rest option

     
  • Anonymous

    Anonymous - 2013-01-16

    Originally posted by: georgian...@gmail.com

    thanks, work fine.

    ... and how do I set default value for Combo Box ?

     
  • Anonymous

    Anonymous - 2013-01-23

    Originally posted by: n3tw0rk...@gmail.com

     

    Last edit: Anonymous 2017-07-10
  • Anonymous

    Anonymous - 2013-02-21

    Originally posted by: nerunblogs

    PassoUm(){

            PASTA_FORM=$(yad --width=570 --height=300\
                                    --form\
                                    --field="Pasta de Trabalho:DIR"\
                                    --title="Criador de Pacotes Debian - 1º Passo"\
                                    --image-on-top --image="Package.png"\
                                    --button="gtk-close:0" --button="gtk-ok:1"\
                                    --text=" Os pacotes Debian são criados a partir dos arquivos de uma
     pasta no seu micro. Dentro dessa pasta você monta uma
     estrutura de diretórios similar ao do seu sistema, mas
     colocando apenas as pastas onde o seu programa instalará
     arquivos. O instalador extrairá os arquivos para as pastas
     indicadas.
    
     <b>Exemplo:</b> se quiser instalar um programa chamado
     'exemplo' em '/opt', crie uma pasta chamada 'pacote' em 
     algum lugar do seu micro (geralmente na pasta de usuário),
     e dentro dela crie a pasta '/opt/exemplo'.
    
     Agora crie sua Pasta de Trabalho e depois selecione-a a
     seguir:")
            ret=$?
    
            echo "$PASTA_FORM" | cut -d"|" -f 1 > /tmp/teste.tmp
    
            if [ $ret -eq 1 ]; then # 1 = OK
                    pasta=$(echo "$PASTA_FORM" | cut -d"|" -f 1)
                    PassoMeio $pasta
            else # 0 = close
                    exit
            fi
    
    }
    

    When i use this code, pasta=$(echo "$PASTA_FORM" | cut -d"|" -f 1) is always null. Doesn't matter wich folder i choose. What happens?

    Uh, and /tmp/teste.tmp always write /home/user/Desktop

     
  • Anonymous

    Anonymous - 2013-02-21

    Originally posted by: nerunblogs

    SOLVED: i removed: --button="gtk-close:0" --button="gtk-ok:1"\ don't need it

     
  • Anonymous

    Anonymous - 2013-02-21

    Originally posted by: ananasik

    if you set your own buttons, remember that only buttons with even exit codes prints result. this is default behavior that may be changed by specifying --always-print-result.

     
  • Anonymous

    Anonymous - 2013-02-24

    Originally posted by: hpp3.mar...@gmail.com

    A few changes to the Run dialog example... I couldn't get it to populate the history, so swapped '--entry' and '--editable'. Now history shows up, but doesn't populate properly (spaces seen as new lines?), so I used the --rest option instead and read the $HISTFILE directly, eliminating the need for eval'ing. I also used a trick to put the last command used at the head of the file, so it shows up as the first entry in the combo box.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    #! /bin/bash
    
    XTERM="xterm"
    
    # create history file 
    mkdir -p ${XDG_CACHE_HOME:-$HOME/.cache}/ 
    HISTFILE=${XDG_CACHE_HOME:-$HOME/.cache}/ix-run.history 
    touch $HISTFILE
    
    # create and run dialog 
    TITLE="Run command" 
    TEXT="\nEnter command to execute:\n" 
    rcmd=$(yad --width=500 --center --window-icon="gtk-execute" --name="${0##/}" --title="$TITLE" --text="$TEXT" --image="gtk-execute" --editable --entry --rest $HISTFILE)
    
    [-z "$rcmd" ] && exit 0
    
    # run command 
    case $rcmd in
        http://*|https://*|ftp://*)
            xdg-open $rcmd & 
            ;;
        mailto://*)
            xdg-email $rcmd & 
            ;;
        man://*)
            eval $XTERM -e "man ${rcmd#man://}" & 
            ;;
        telnet*|ssh*)
            eval $XTERM -e "$rcmd" & 
            ;;
        *)
            eval $rcmd & 
            ;;
    esac
    
    # add command to history 
    head $HISTFILE | grep -qF "$rcmd" || echo -e "$rcmd\n$(<$HISTFILE)" > $HISTFILE
    
    exit 0
    

    I changed the grep line because if a command is buried down in the history, I wanted to allow it writing to the file even if the command exists farther down; for convenience. I also think the file should be kept trim with a 'head -n' command; I tried to feed my bash history to it and it threw an error. ;)

     
  • Anonymous

    Anonymous - 2013-02-25

    Originally posted by: ananasik

    yes, now --rest is a better choice than perl && eval. and for adding command at the begin of history file, i use sed - sed -i "1 i $rcmd" $HISTFILE

     
  • Anonymous

    Anonymous - 2013-04-11

    Originally posted by: jbs...@gmail.com

    Anyone can help me with this?

    So basically this BASH script works fine, Debian boots into a minimal Matchbox WM environment and this script is autorun which displays a nice graphical prompt allowing entry of AD username and pass, and then the vars get passed to pyhoca-cli which logs the computer into a remote x2go-server linux terminal server.. it works without issue.

    However what I want to do is add an additional drop-down selection to the YAD graphical prompt (after the first two fields), where the user can select the session (eg kde, xfce4, lxde & fluxbox), and then pass that selection to the pyhoca-cli command to replace startkde with something like start$frmdata (from the dropdown selection)...

    Not sure exactly how to do this...

    root@lxtrms-thinclient-colodesk:~# cat /home/colodesk/start_pyhoca.sh
     #!/bin/bash
    while true; do
    frmdata=$(yad --center --undecorated --image=/usr/share/wallpaper/header-mod.jpg --image-on-top --button="gtk-ok:0" --title "Login to Linux Terminal Server" --form --field="AD username" --field="Password:H")
    frmusername=$(echo $frmdata | awk 'BEGIN {FS="|" } { print $1 }')
    frmpassword=$(echo $frmdata | awk 'BEGIN {FS="|" } { print $2 }')
    pyhoca-cli --server some.private.ip.addr -u $frmusername --password $frmpassword -c startkde --sound none --kbd-layout us --kbd-type pc105/us -g fullscreen --add-to-known-hosts
    done
    
     
  • Anonymous

    Anonymous - 2013-05-02

    Originally posted by: macke...@gmail.com

    Here is a process killer to select one (or more) pids and kill them:

    !/bin/bash

    TMPFILE=/tmp/$$.pstmp OUTFILE=/tmp/$$.psdata EMSG=/tmp/$$.errmsg

    gen_data() {

    ps aux | tail -n +2 > $TMPFILE

    cat $TMPFILE | awk -F' ' '{print " " "\n" $1 "\n" $2 "\n" $3 "\n" $4 "\n" $5 "\n" $6 "\n" $7 "\n" $8 "\n" $9 "\n" $10 "\n" $11}' > $OUTFILE

    }

    while true do

    gen_data

    selection=$( yad --list \

    --checklist \

    --column=":CHK" \ --column="USER:TXT" \ --column="PID:NUM" \ --column="%CPU:NUM" \ --column="%MEM:NUM" \ --column="VSZ:NUM" \ --column="RSS:NUM" \ --column="TTY:TXT" \ --column="STAT:TXT" \ --column="START:TXT" \ --column="TIME:TXT" \ --column="COMMAND:TXT" \ --multiple \ --width=900 \ --height=600 \ --title="Killer" \ --window-icon="process-stop" \ --button="Kill:0" \ --button="Refresh:1" \ --button="Exit:2" < $OUTFILE)

    sel_ret=$?

    case $sel_ret in

    0)

    echo "$selection" | awk -F'|' '{print $3 " " $12}' | while read pid cmd do

    if -n "$pid" then

    zenity --question --text "Confirm kill of pid: $pid\n\nCommand: $cmd" rc=$? if $rc -eq 0 then

    kill -9 $pid 2> $EMSG if $? -ne 0 then

    errmsg="cat $EMSG" zenity --error --text "$errmsg"

    else

    zenity --info --text "Pid $pid killed..." --timeout=1

    fi

    fi

    else

    zenity --info --text "No pid selected..." --timeout=3

    fi

    done ;;

    1. continue ;;

    2)

    break ;;

    esac

    done

    rm -f $TMPFILE rm -f $OUTFILE rm -f $EMSG

     
  • Anonymous

    Anonymous - 2013-05-20

    Originally posted by: yarling....@gmail.com

    Hi. I created a start and stop button interface. So when I clicked on the start button, my program is executing but the interface is gone. How can I make the interface remain so that I can stop my program using the stop button in the interface? Thanks.

     
  • Anonymous

    Anonymous - 2014-01-27

    Originally posted by: ekia...@gmail.com

    It would be great if yad could display icons/tiny pictures in "lists" - so that one can for example display a thumbnail in a column, and the name of the file in another. Would that be possible to implement ?

     
  • Colin Keenan

    Colin Keenan - 2014-09-15

    I've read the man page and examples here and elsewhere, but really, there should be quick example usage for each option. Right now, I can't get --show-uri to work. Can anyone post a simple example of --show-uri in the --text-info dialogue? This doesn't work:

    yad --info-text --show-uri --text="https://www.google.com/"
    
     
  • Brian Stewart

    Brian Stewart - 2016-04-04

    I'm trying to use a numerical input field with a range of -5 to +10 and with an initial value of -2. I can get yad to set the range with the -5..10 range but I cannot get the initial value to be a negative number. It always seems to start with an initial value of 0.
    What am I doing wrong?

    yad --title="Negative number test" --form --field="number:NUM" "(-2)!-5..10!1!0"

     

    Last edit: Brian Stewart 2016-04-04
    • Victor Ananjevsky

      don't use brackets. separate data from options with two dashes if you have data started with dash

      yad --title="Negative number test" --form --field="number:NUM" -- "-2!-5..10!1!0"

       
  • Brian Stewart

    Brian Stewart - 2016-04-04

    Thank you, thank you, thank you!!!
    I knew this had to be something stupid on my part.
    I had tried using variables, expressions brackets etc.
    I'm new to bash and didn't know about the "--". I won't forget it now.

     
  • wseverin

    wseverin - 2017-12-07

    I've been a frequent user of zenity and just a few days ago decided to see what I could do with yad. Here is the fruit – a simple random password generator that lets the user pick symbol sets and some constraints. I'm sure there are better ways to do some of the things here, but it may be a helpful example for future yad users. This works with yad 0.38.2 on Ubuntu 17.10 (Artful).

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    #!/bin/bash
    
    # put following code into temporary file and make executable
    echo '#!/bin/bash
    
    declare -a ARGS USEDSYM
    
    UC="ABCDEFGHJKLMNPQRSTUVWXYZ" # excludes "I" and "O"
    LC="abcdefghijkmnopqrstuvwxyz" # excludes "l"
    NUM="0123456789"
    HEX="ABCDEF"
    SPEC="!@#$%-&."
    
    function reqChar {
      local i i0 ix j
      FROMSET="$1"
      GOOD=FALSE
      i0=$(( $RANDOM * PWLEN / 32768 ))
      for ((ix=i0;ix<PWLEN+i0;ix++)); do
        i=$(( ix % PWLEN ))
        if [ "${FROMSET#*${PW:$i:1}}" != "$FROMSET" ]; then
          GOOD=TRUE
          USEDSYM[i]=1
          break
        fi
      done
    
      if [ $GOOD = FALSE ]; then
        i0=$(( $RANDOM * PWLEN / 32768 ))
        for (( ix=i0;ix<i0+PWLEN;ix++)) ; do
          i=$(( ix % PWLEN ))
          if [ -z ${USEDSYM[i]} ]; then
            j=$(( $RANDOM * ${#FROMSET} / 32768 )) # a random character to replace it with
            PW="${PW:0:$((i))}${FROMSET:j:1}${PW:$((i+1))}"
            USEDSYM[i]=1
            break
          fi
        done
      fi
    }
    
    # pwgen-exec main
    # args: PWLEN USEUC USELC USENUM USEHEX USESPEC RQUC RQLC RQNUM RQSPEC
    
    i=0
    for arg in "$@"; do
      ARGS[i++]=$arg
    done
    
    # determine base symbol set
    PWLEN=${ARGS[0]}
    SYMSET=""
    if [ "${ARGS[1]}" = "TRUE" ]; then SYMSET="${SYMSET}${UC}"; fi
    if [ "${ARGS[2]}" = "TRUE" ]; then SYMSET="${SYMSET}${LC}"; fi
    if [ "${ARGS[3]}" = "TRUE" ]; then SYMSET="${SYMSET}${NUM}"; fi
    if [ "${ARGS[4]}" = "TRUE" ]; then SYMSET="${SYMSET}${HEX}"; fi
    if [ "${ARGS[5]}" = "TRUE" ]; then SYMSET="${SYMSET}${SPEC}"; fi
    SYMLEN=${#SYMSET}
    
    PW=""
    for ((i=0;i<PWLEN;i++)); do
      PW=${PW}${SYMSET:(( $RANDOM % SYMLEN )):1}
    done
    
    # comply with constraints
    USEDSYM=( )
    if [ "${ARGS[6]}" = "TRUE" ]; then reqChar "$UC"; fi
    if [ "${ARGS[7]}" = "TRUE" ]; then reqChar "$LC"; fi
    if [ "${ARGS[8]}" = "TRUE" ]; then reqChar "$NUM"; fi
    if [ "${ARGS[9]}" = "TRUE" ]; then reqChar "$SPEC"; fi
    
    if [ ${#PW} = 0 ]; then PW="nonsense"; fi
    echo "16:${PW}"' > /tmp/pwgen-exec
    
    chmod 777 /tmp/pwgen-exec
    
    yad --title="PWGen" --center \
      --form \
        --field="password length:NUM" \
        --field="<b>select base character set(s)</b>:LBL" \
        --field="uppercase alpha:CHK" \
        --field="lowercase alpha:CHK" \
        --field="numeric:CHK" \
        --field="A-F:CHK" \
        --field="special:CHK" \
        --field=":LBL" \
        --field="<b>select constraint(s)</b>:LBL" \
        --field="at least one uppercase:CHK" \
        --field="at least one lowercase:CHK" \
        --field="at least one numeric:CHK" \
        --field="at least one special:CHK" \
        --field=":LBL" \
        --field="gtk-execute:FBTN" \
        --field=":TXT" \
        "8!4..132"  "" TRUE TRUE TRUE FALSE FALSE "" "" FALSE FALSE TRUE FALSE "" \
        '@bash -c "/tmp/pwgen-exec %1 %3 %4 %5 %6 %7 %10 %11 %12 %13"' \
        "password" \
        --button="Exit:1"
    
    rm -f /tmp/pwgen-exec
    exit 0
    
     
<< < 1 2 3 (Page 3 of 3)

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.