Skip to content

Instantly share code, notes, and snippets.

@jesboat
Created November 29, 2011 23:04
Show Gist options
  • Save jesboat/1407050 to your computer and use it in GitHub Desktop.
Save jesboat/1407050 to your computer and use it in GitHub Desktop.
Roughly equivalent to "find .", only in less-than-POSIX ash
#!/system/bin/sh
stat() {
local lsout="$(ls -ld "$1" 2>/dev/null)"
case "$lsout" in
"") nex=1; fil= ; dir= ;;
d*) nex= ; fil= ; dir=1 ;;
*) nex= ; fil=1; dir= ;;
esac
}
nonempty() {
case "$1" in
"") return 1 ;;
*) return 0 ;;
esac
}
flagset() {
local vname="$1"
local vval="$(eval "echo \$$vname")"
nonempty "$vval"
}
forglob() {
local root="$1"
shift
for ent in "$root"/* "$root"/.*; do
case "$ent" in
*/.) true ;;
*/..) true ;;
*)
# If the directory's empty, the glob expanded
# to ".../*" which doesn't exist. Rule it out.
stat "$ent"
if ! flagset nex; then
cur="$ent"
eval "$*"
fi
;;
esac
done
}
oneent() {
if flagset dir; then
local d="$cur"
hasfiles=
forglob "$d" "hasfiles=1"
if flagset hasfiles; then
echo "$d"
forglob "$d" oneent
fi
else
echo "$cur"
fi
}
cur=.
stat .
oneent
@jesboat
Copy link
Author

jesboat commented Nov 29, 2011

This script (written for the ash in Android Honeycomb, which is missing many POSIX features) is roughly equivalent to find ., except that it omits empty directories. (The omission is intentional; if you'd rather see them too, change flagset hasfiles to true or something like that.)

Challenges included working without test (aka [), including not only an inability to write if [ -d "$foo" ] ... but also missing if [ "$v" = something ] !

Also some ugliness with globbing, since we have to implement bash's nullglob and dotglob. There's also no ${!indirect} support. And I hate not having real lexical scope.

Yeah that's all.

@jesboat
Copy link
Author

jesboat commented Nov 29, 2011

The use case is

# Get the list of files (and their parent dirs) on the sdcard
adb push find-in-ash.noemptydirs.sh /mnt/sdcard
adb shell
  cd /mnt/sdcard
  sh find-in-ash.noemptydirs.sh > filelst
  exit
adb pull /mnt/sdcard/filelst filelst.there

# Make a local copy of the sdcard, for backup
adb pull /mnt/sdcard/ sdcard

# Make sure we got everything
(cd sdcard && find .) > filelst.here
diff <(sort filelst.there) <(filelst.here)

(Yes, it sounds like it's just doing an extra check for paranoia, but adb actually missed some things the first time around. Not particularly encouraging.)

This would have been a lot simpler if toolbox (Android's BusyBox wanna-be) had tar, or if there was an obvious way to mount a Xoom's internal memory as USB Mass Storage. But this was fun, at least.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment