How can I create a bash (NOT GUI!) file picker that allows a user to pick one and ONLY one file, which may have spaces in the filename?

How can I create a bash (NOT GUI!) file picker that allows a user to pick one and ONLY one file, which may have spaces in the filename?:

This has been driving me crazy for the past 24 hours or so. I am trying to make this work under Ubuntu SERVER 16.04. Please note there is no desktop or GUI on this system, and I need this to work over an SSH connection.

What I want to do is display a list of files in a particular directory that have a particular extension, and let the user pick one and ONLY one file from that list. The files should be displayed as filename and extension only.

I have been trying to use whiptail for this (because it comes in the Ubuntu Server 16.04 distro) but while I can get it to work for files that do not have spaces in them, it completely fails if any filename in the directory has spaces in it. Here is an example of something I have tried:

#!/bin/bash shopt -s nullglob cd /path/to/some/directory array=(*.png) 

(Note that if at this point I include a line like the following, it shows all the files, one per line whether or not they have spaces)

for ((i=0; i<${#arr[@]}; i++)); do echo "${arr[$i]}" ; done 

So apparently the above is fine, it’s this next line where everything falls apart:

result=$(whiptail --title "Select File" --backtitle "File Selector" --menu "Select the file from the list below:" 20 80 10 $arr 2>&1 >/dev/tty) 

The problem is that whiptail breaks the filenames at weird places, I can’t explain it very well but it seems rather random. Where you see $arr I have tried some other variations such as ${arr[@]} but either whiptail doesn’t work at all, or it shows partial filenames or multiple filenames seemingly split in random places.

My end goal is that the user can move the arrow keys to the desired filename and hit Enter and the the filename will be returned in the $result variable (if they tab to OK first and then hit Enter, that’s fine too). But either I am doing something very wrong in whiptail, or whiptail has some bugs in the way it displays items with spaces in an array

I’m not married to whiptail here, but I cannot use something that requires a desktop or GUI and therefore can’t work over a plain ssh connection. Any suggestions on how I can get this to work would be greatly appreciated.

submitted by /u/AStrowger
[link] [comments] via Linux 101 stuff. Questions are encouraged, noobs are welcome!

Posted in IFTTT, Linux 101 stuff. Questions are encouraged, noobs are welcome!