How to use zenity file selection
Solution 1:
In order to save the output of a command in a variable, you must enclose the command in backtics (`command`
) or, better, in $()
($(command)
). You are using single quotes which means that you are saving the string wc $FILE
and not actually running wc
:
$ foo='wc /etc/fstab' ## WRONG
$ echo $foo
wc /etc/fstab
$ foo=`wc /etc/fstab` ## RIGHT
$ echo $foo
23 96 994 /etc/fstab
$ foo=$(wc /etc/fstab) ## RIGHT
$ echo $foo
23 96 994 /etc/fstab
In addition, in order to get only the words and not the number of characters and lines, use the -w
option:
$ foo=$(wc -w /etc/fstab)
$ echo $foo
96 /etc/fstab
Finally, to get the number alone, with no file name, you can use:
$ foo $(wc -w /etc/fstab | cut -d ' ' -f 1 )
$ echo $foo
96
Solution 2:
I think that the correct code may be this:
#!/bin/bash
function count() {
word_count=$(wc -w < "$FILE")
zenity --info --title="Word Counted" --text="Counted words $word_count"
}
function choose() {
FILE="$(zenity --file-selection --title='Select a File')"
case $? in
0)
count;;
1)
zenity --question \
--title="Word counter" \
--text="No file selected. Do you want to select one?" \
&& choose || exit;;
-1)
echo "An unexpected error has occurred."; exit;;
esac
}
choose