对话框菜单显示文件并选择其中之一

对话框菜单显示文件并选择其中之一

我想在菜单中显示目录下的所有文件/home,并只选择其中一个。然后脚本将打印所选文件的完整路径。

我创建了以下脚本。该脚本仅显示对话框菜单中的文件。

#!/bin/bash
dialog --title "List file of directory /home" --msgbox "$(ls /home )" 100 100

答案1

对话有文件选择和目录选择小部件(如 Xdialog):

使用 --fselect 的对话框图片

要使用它,OP的脚本可能是

#!/bin/bash
dialog --title "List file of directory" --fselect /home 100 100

尽管 100x100 的窗口看起来相当大。这手册页提供更好的替代方案:

大多数小部件接受高度和宽度参数,这些参数可用于自动调整小部件的大小以适应多行消息提示值:

  • 如果参数为负数,对话框将使用屏幕的尺寸。
  • 如果参数为零,对话框将使用小部件的最小尺寸来显示提示和数据。
  • 否则,对话框将使用小部件的给定大小。

如果您想将自己限制为可以使用 运行的脚本whiptail,则该--radiolist选项是 的替代方案--menu

答案2

您应该使用菜单而不是消息框。试试这个脚本:

#!/bin/bash
let i=0 # define counting variable
W=() # define working array
while read -r line; do # process file by file
    let i=$i+1
    W+=($i "$line")
done < <( ls -1 /home )
FILE=$(dialog --title "List file of directory /home" --menu "Chose one" 24 80 17 "${W[@]}" 3>&2 2>&1 1>&3) # show dialog and store output
RESULT=$?
clear
if [ $RESULT -eq 0 ]; then # Exit with OK
     echo "${W[$((FILE * 2 -1))]}"
fi

数组在这里是必需的,否则它不会正确解析为命令,请参阅http://mywiki.wooledge.org/BashFAQ/050

脚本列出了 /home 文件夹中的所有内容,与您的示例相同。如果您确实只想要文件,请替换

ls -1 /home 

find /home -maxdepth 1 -type f

还请考虑使用“whiptail”,因为它是大多数发行版中的默认选项。Dialog 大多未安装。

相关内容