Home > other >  Why can't I use this text from zenity to find files?
Why can't I use this text from zenity to find files?

Time:08-11

I want to use the zenity text input for file selection so i can just drag and drop. Seems like it should work but doesn't. When I drag in a file it doesn't find it, but the path and file name seem correct.

The "cut" is to remove the leading "file:/" from the input text.

xinput=$(zenity --entry \
--title="Drag in file" \
--text="" \
--entry-text "" \ )

xfile=$(echo "$xinput" | cut -c 7-)

if test -f "$xfile"; then
   echo "Found!"
else 
   echo "Not Found!"
fi
echo $xfile

CodePudding user response:

It seems like zenity prepends file:// and appends \r to the file path. It also converts all potentially problematic characters to their url-encoded version.

#!/bin/bash

xinput=$(
    zenity --entry \
    --title="Drag in file" \
    --text="" \
    --entry-text ""
)

# extract the part of interest
[[ $xinput =~ ^file://(.*)$'\r'$ ]] || exit 1

# decode the string
printf -v xfile "${BASH_REMATCH[1]//%/\\x}"

if [[ -e "$xfile" ]]
then
    printf '%q\n' "$xfile"
else
    printf 'No such file or directory: %q\n' "$xfile"
fi

remark: I tested the code with a path containing all the ASCII characters (0x01 to 0x7F)

  • Related