Why zenity color selection piping to sed breaks the code?

853 views Asked by At

I am trying use sed to convert 12 digit hex code returned from zenity's --color-selection dialogue into 6 digit hex code. for example: #dfe251a951a9 to #df5151. but as soon as i use sed in the following code it breaks the whole script, and when i select "select" or "cancel" buttons i dont get respective echo! what's the problem?

before using sed: everything works nice but i get 12 digit hex code.

#!/bin/bash
color=$(zenity --color-selection)
if [[ $? == 0 ]]
then 
    echo "You selected $color."
else [[ $? == 1 ]]
    echo "No color selected."
fi

after using sed: when i hit select button i get 6 digit hex code but when i hit cancel i dont get "no color selected", it echoes "You selected ."

#!/bin/bash
color=$(zenity --color-selection | sed 's/\(#\?..\)../\1/g')
if [[ $? == 0 ]]
then 
    echo "You selected $color."
else [[ $? == 1 ]]
    echo "No color selected."
fi
1

There are 1 answers

2
Wintermute On BEST ANSWER

After

color=$(zenity --color-selection | sed 's/\(#\?..\)../\1/g')

$? is the exit status of sed (not zenity)1, which is 0. You could use

#!/bin/bash
color=$(zenity --color-selection)

# Now $? is the exit status of zenity
if [[ $? == 0 ]]
then
    # Process with sed only if necessary.
    color=$(echo "$color" | sed 's/\(#\?..\)../\1/g')
    echo "You selected $color"
else
    echo "No color selected."
fi

Note, by the way, that my version of zenity (3.16.2) does not return a hexadecimal code but something of the form rgb(12,34,56). I have not investigated when or why this change happened, but it may not be wise to rely on a particular format.

1 More precisely: It's the exit status of the subshell spawned by $(), which just forwards the exit status of the last command it ran: the sed call.