Tuesday, February 28, 2023

Finally: USB Thumbdrive Access from within Termux

One maddening exercise in Termux is inserting a USB Thumb drive into your phone: it will be recognized by Android, but invisible to Termux.

See, My Files on my S22 Ultra recognizes the USB reader:

Termux, despite re-executing termux-setup-storage, doesn't.

Grrrrr.

The usual suggestion to overcome this shortcoming is to root your phone; something I'm not ready to do (yet). Thankfully, after years of running into this issue, I finally found an easy, no-root, work around. Here's the fix in action:

In the above screenshot, you can see I'm interacting with the USB thumdrive via the command fsops and the path /mnt/media_rw/B601-0C66.

fsops is my own creation, which you can find on github. It supports listing, copying, cat'ing and removing files. It plays nice with other bash commands so you can use it as part of one-liners or scripts in general.

fsops works because of two truths. First, Tasker, like my phone's file browser, can see USB drives. When I launch a File Select action in Tasker, it let's me click on the icon in the bottom right corner to browse the USB drive:

Incidetanlly, that's how I learned the magic path /mnt/media_rw/B601-0C66.

Next, it's possible to invoke Tasker from Termux's command line (including from within a proot'd Linux instance). This post explains how. The mechanism in use here is Android intents. You can set up a Tasker profile to listen for net.dinglish.tasker.Xyz and then invoke:

am broadcast --user -a net.dinglish.tasker.Xyz

To call the Xyz profile. fsops invokes tasker with the following parameters:

am broadcast --user 0 -a net.dinglish.tasker.FileSystemOperation \
	-e operation "$op" \
	-e outcome "$outcome" \
        -e error "$error" \
	-e src "$src" \
	-e dest "$dest" > /dev/null

op is set to the operation I want to perform and the remaining variables are set to files that will either be set by the user or filled in by fsops.

am broadcast delivers data to Tasker, which invokes my file system operation of choice. am broadcast makes no promises about when the task will be finished. To overcome this limitation, fsops passes a path in the variable $outcome and polls the existence of this file to detect when the task is done. While a bit on the brute force side of things, it does work well.

You can grab fops here, and the Tasker resources here. Once set up, that thumbdrive will finally be available in Termux. Whoo!

No comments:

Post a Comment