I am writing a shell script that is meant to prompt the user for a file, and since I do not expect the end user of my script to be tech-savvy, rather than starting command line for interaction, I would like the shell to be able to summon the system File manager in a standard way (e.g. using xdg or similar) that would open it in an "Open file..."-like dialog, and output the full or relative path to a file or directory once one was selected. Is there a way to do this either in a Linux or MacOS, or both?
1 Answer
You can do this on macOS by using the osascript command to run AppleScript's choose file command. Something like this:
if filepath=$(osascript -e 'POSIX path of (choose file with prompt "Pick a file:")'); then
echo "Your file is: $filepath"
ls -l "$filepath"
else
echo "Cancelled."
fi
Note that if the user cancels the selection dialog (or something else goes wrong), osascript will print an error message to stderr (as well as exiting with an error status, which is what the if test above checks), so you may want to redirect error output to suppress or capture this.
Also, macOS file names and paths often contain spaces, so be sure to put double-quotes around all your variable references (e.g. ls "$filepath" rather than just ls $filepath). This is good scripting hygiene in general, but particularly important here. shellcheck.net is good at spotting common mistakes like unquoted variable references, so I recommend running your scripts past it to see what it recommends.
For more info about the choose file command, see Apple's Mac Automation Scripting Guide: Prompting for Files or Folders.
-
Marked as answer. that last link is exactly what I was looking for! thank you, and will add to this if I figure out a linux portable solution.fja– fja2024-05-04 15:50:04 +00:00Commented May 4, 2024 at 15:50
xdg-opendo what you want? Why is the file manager needed? Will the user give a full path? A file name? Why would you want to prompt the user instead of reading arguments from the command line so they can use tab completion?osascriptcommand, none of which exists on any Linux.