如何从“ls”加载带有空间嵌入数据的“zenity”列表对话框?

如何从“ls”加载带有空间嵌入数据的“zenity”列表对话框?

zenity当数据包含空格时, 加载列表对话框会遇到问题。

当列出的数据中没有空格时,这很简单,
但我不知道嵌入空格的文件名的简单/标准方法。

由于某种原因,$( ) 的输出ls -Q /tmp(带引号的输出)仍然会
在每个空格处拆分文件名。输出中的引号和反斜杠
ls | sed似乎被视为“最终字符串”,而不是
“可读数据行”(如前两行数据)...

我已经设法“解决这个问题”,但自我修改代码可能
不是最好的方法!(尽管它很有趣!:)


这是不起作用的方法

zenlist="/tmp/zen list"; touch "$zenlist"
zenity --list --title='A single-column List' --width=600 --height=450 \
--column='Spaces are allowed within "q u o t e s"' \
"How much wood would a woodchuck chuck," \
"if a wooodchuck could chuck wood?" \
$(ls -Q -1 "$zenlist"* |sed 's/$/ \\/')
echo ""
# rm "$zenlist"  # Uncomment this line to delete the file

这种方法可行,但一定有“常规”(更好)的方法!?

zenlist="/tmp/zen list"
echo "zenity --list --title='A single-column List' --width=600 --height=450 \\" >"$zenlist"
echo "--column='Spaces are allowed within \"q u o t e s\"' \\"       >>"$zenlist"
echo "\"How much wood would a woodchuck chuck,\" \\"       >>"$zenlist"
echo "\"if a wooodchuck could chuck wood?\" \\" >>"$zenlist"
(ls -Q "$zenlist"* |sed 's/$/ \\/')   >>"$zenlist"
echo "" >>"$zenlist"
source "$zenlist"
# rm "$zenlist"  # Uncomment this line to delete the file

答案1

问题是ls。它从来就不是为在脚本中使用而设计的。此外,在脚本中使用它也毫无意义ls,因为 shell 可以做得更好,只需使用 glob 即可,请参阅http://mywiki.wooledge.org/BashGuide/Patterns

zenlist="/tmp/zen list"; touch "$zenlist" "$zenlist"$'\neven with a newline'
zenity --list --title='A single-column List' --width=600 --height=450 \
       --column='Spaces are allowed within "q u o t e s"' \
       "How much wood would a woodchuck chuck," \
       "if a wooodchuck could chuck wood?" \
       "$zenlist"*

将带有空格和其他字符的列表项放入“变量”的一般方法是使用 bash 数组。

# assign some items to start with
items=( "How much wood would a woodchuck chuck," "if a wooodchuck could chuck wood?" )

# append some items
items+=( "$zenlist"* )

zenity --list --title='A single-column List' --width=600 --height=450 \
       --column='Spaces are allowed within "q u o t e s"' "${items[@]}"

答案2

您可以将列表内容导入 zenity,例如

(echo "How much wood would a woodchuck chuck," ; \
 echo "if a wooodchuck could chuck wood?" ; \
 ls -Q -1 "$zenlist"* |sed 's/$/ \\/') \
| zenity --list --title='A single-column List' --width=600 --height=450 \
         --column='Spaces are allowed within "q u o t e s"'

相关内容