#!/usr/bin/env bash
start_dir="${1:-$PWD}"
tmpfile=$(mktemp)
trap 'rm -f "$tmpfile"' EXIT
current="$start_dir"
while true; do
entries=()
i=1
entries+=(".. (parent)" "DIR")
while IFS= read -r -d '' item; do
name=$(basename "$item")
if [ -d "$item" ]; then
entries+=("$i" "$name/")
else
entries+=("$i" "$name")
fi
i=$((i+1))
done < <(printf '%s\0' "$current"/* 2>/dev/null)
choice=$(dialog --clear --title "File browser: $current" \
--menu "Select an entry:" 20 60 16 "${entries[@]}" 2>&1 >/dev/tty)
exit_status=$?
if [ $exit_status -ne 0 ]; then
clear
exit 0
fi
if [ "$choice" = ".. (parent)" ]; then
current=$(dirname "$current")
continue
fi
idx=$choice
sel_path=$(printf '%s\0' "$current"/* | awk -v idx="$idx" -v RS='\0' 'NR==idx{print; exit}')
if [ -z "$sel_path" ]; then
dialog --msgbox "Selection not found." 6 40
continue
fi
if [ -d "$sel_path" ]; then
current="$sel_path"
continue
fi
action=$(dialog --menu "File: $(basename "$sel_path")" 12 60 6 \
1 "View (textbox)" 2 "Print path to stdout" 3 "Save path to file" 4 "Delete file" 5 "Cancel" 2>&1 >/dev/tty)
case "$action" in
1)
dialog --title "$(basename "$sel_path")" --textbox "$sel_path" 0 0
;;
2)
clear
printf '%s\n' "$sel_path"
exit 0
;;
3)
outfile=$(dialog --inputbox "Save path to which file?" 8 60 2>&1 >/dev/tty)
if [ -n "$outfile" ]; then
printf '%s\n' "$sel_path" > "$outfile"
dialog --msgbox "Saved to $outfile" 6 40
fi
;;
4)
dialog --yesno "Delete $(basename "$sel_path")?" 7 50
if [ $? -eq 0 ]; then
rm -f -- "$sel_path" && dialog --msgbox "Deleted." 6 30 || dialog --msgbox "Delete failed." 6 30
fi
;;
*)
;;
esac
done