Skip to content

Instantly share code, notes, and snippets.

@qianbinbin
Last active February 21, 2023 13:22
Show Gist options
  • Save qianbinbin/e93e19940dda264cc5cd2ebdddbe565e to your computer and use it in GitHub Desktop.
Save qianbinbin/e93e19940dda264cc5cd2ebdddbe565e to your computer and use it in GitHub Desktop.
Android shell script to unmount all external SD card(s)

The script may not work for Android < 6.0.

Simply run unmount.sh in Android terminal to unmount all external SD card(s), partitions formated as internal will be ignored.

To unmount when system starting up, put the script in /data/adb/service.d/ (Magisk root required) and execute chmod +x /data/adb/service.d/unmount.sh. This will be useful if Linux Deploy installs in a SD card partition.

To turn on logs, change LOG_ON=false to LOG_ON=true, the log file will be /data/local/tmp/unmount.log.

#!/system/bin/sh
LOG_ON=false
LOG_FILE=/dev/null
[ "$LOG_ON" = true ] && LOG_FILE=/data/local/tmp/unmount.log
log() {
while IFS= read -r; do
echo "[$(date +%T)] $REPLY" | tee -a "$LOG_FILE"
done
}
if [ "$(getprop ro.build.version.sdk)" -lt 23 ]; then
echo "The script may not work for Android < 6.0" | log
echo "Current version: $(getprop ro.build.version.release)" | log
fi
(
until [ "$(getprop sys.boot_completed)" -eq 1 ]; do
echo "Waiting until boot completed..." | log
sleep 5
done
echo "Trying unmounting all public volumes for 5 times anyway..." | log
for i in $(seq 5); do
echo "[$i]" | log
vols=$(sm list-volumes public)
if [ -z "$vols" ]; then
echo "No public volumes found." | log
else
echo "Public volumes:" | log
echo "$vols" | log
echo "$vols" | while IFS= read -r line; do
vol=$(echo "$line" | cut -d " " -f 1)
state=$(echo "$line" | cut -d " " -f 2)
if [ "$state" = unmounted ]; then
echo "Ignoring unmounted: $vol" | log
continue
fi
echo "Unmounting: $vol" | log
sm unmount "$vol" 2>&1 | log
echo "State:" | log
sm list-volumes public | grep "$vol" | log
done
fi
sleep 5
done
) &
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment