Eka*_*Eka 7 bash scripts files zenity
我是新手zenity,我正在尝试制作一个简单的脚本来加载文件,zenity --file-selection并使用wc命令来获取该文件的字数。我已经成功制作了一个可用于浏览文件的表单,但我无法获得任何输出。你能告诉我我在哪里犯了错误吗?
我目前的脚本是:
#creates a box
if zenity --entry \
--title="Word count" \
--text="Enter file location" \
--entry-text "File path"
then
#Zenity file selection code for browsing and selecting files
FILE=`zenity --file-selection --title="Select a File"`
case $? in
0)
echo "\"$FILE\" selected.";;
1)
echo "No file selected.";;
-1)
echo "An unexpected error has occurred.";;
esac
# To show the location in the text box
if zenity --entry \
--title="Word count" \
--text="Enter file location" \
--entry-text "$FILE"
then
#word counting code
word_count='wc $FILE'
zenity --info --title="Word Counted" --text="Counted words $word_count"
fi
fi
Run Code Online (Sandbox Code Playgroud)
为了将命令的输出保存在变量中,您必须将命令括在反引号 ( `command`) 中,或者更好地用$()( $(command))括起来。您使用的是单引号,这意味着您正在保存字符串 wc $FILE而不是实际运行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
Run Code Online (Sandbox Code Playgroud)
另外,为了只获取单词而不是字符和行数,请使用-w选项:
$ foo=$(wc -w /etc/fstab)
$ echo $foo
96 /etc/fstab
Run Code Online (Sandbox Code Playgroud)
最后,要单独获取编号,没有文件名,您可以使用:
$ foo $(wc -w /etc/fstab | cut -d ' ' -f 1 )
$ echo $foo
96
Run Code Online (Sandbox Code Playgroud)
我认为正确的代码可能是这样的:
#!/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
Run Code Online (Sandbox Code Playgroud)