Skip to content

Instantly share code, notes, and snippets.

@koonix
Last active July 1, 2021 10:25
Show Gist options
  • Save koonix/73d09cdf2cb53ddbd9cde38d7aefebce to your computer and use it in GitHub Desktop.
Save koonix/73d09cdf2cb53ddbd9cde38d7aefebce to your computer and use it in GitHub Desktop.
[Bash Script] Mount and open android phones automatically. Uses simple-mtpfs(1).
#!/bin/sh
# this script looks for connected android or MTP devices
# for 30 seconds, and mounts them when connected.
# if any device is already mounted, it just opens them.
# requires simple-mtpfs(1).
# config
mnt=~/Mount/MTP
file_manager="${FILE:-xdg-open}"
main ()
{
instances
mountpoints
for i in $(seq 1 30); do
mount
sleep 1
done
tmpcleanup
}
# loop over detected devices,
# then mount and open them.
mount ()
{
for dev in $(simple-mtpfs -l | tr ' ' '%'); do
dir="$mnt/$(echo $dev | cut -d% -f2)-$(shuf -n1 -i10000-99999)"
mkdir -p "$dir"
if simple-mtpfs --device $(echo $dev | cut -d: -f1) "$dir"; then
$file_manager "$dir"
else
rmdir "$dir"
fi
done
}
# open already mounted devices,
# cleanup orphaned mountpoints.
mountpoints ()
{
for dir in "$mnt"/*; do
[ -d "$dir" ] || continue
rmdir "$dir"
file="$dir/test-$(shuf -n1 -i10000-99999)"
if touch "$file"; then
rm -f "$file"
$file_manager "$dir"
else
pkill -f "simple-mtpfs.*$dir?" && sleep 0.2
fusermount -u "$dir"
rmdir "$dir"
fi
done
}
# kill other instances of mmtp.
instances ()
{
pid="${XDG_RUNTIME_DIR:-/tmp}/mmtp-pid"
[ -r "$pid" ] && kill -USR1 -- -$(cat $pid)
trap exit HUP
trap "trap - EXIT; exit" USR1
trap "rm $pid" EXIT
echo $$ > "$pid"
}
# cleanup old simple-mtpfs temp files.
tmpcleanup ()
{
find /tmp -maxdepth 1 -type d -iname 'simple-mtpfs-*' -mtime +1 \
-exec rmdir '{}' ';' 2>/dev/null
}
main "$@"
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment