Skip to content

Instantly share code, notes, and snippets.

@nilium
Created July 24, 2017 17:25
Show Gist options
  • Save nilium/1944d7db1d10c688ef2612246641a5bd to your computer and use it in GitHub Desktop.
Save nilium/1944d7db1d10c688ef2612246641a5bd to your computer and use it in GitHub Desktop.
Dumb little script to find and ostensibly let someone list / recover vim swap files
#!/usr/bin/env bash
# vim: set tw=80 sw=2 ts=2 et :
# USAGE: recover-vim [-h|-help] [CMD...]
#
# See usage text below for more information.
case "$1" in
[-/]h|[-/]help|--help)
cat <<'USAGE'
USAGE: recover-vim [-h|-help] [CMD...]
recover-vim performs a recursive search for .s[a-z][a-z] files and passes them
to the given CMD (all at once). By default, if no CMD is given, vim is invoked
for the swap file's original file to deal with the swap file (either to recover
or delete it, if either). If no files or found, it prints a message to stderr
and exits with status code 0.
If invoked with -h (or -help), it prints this usage text and exits with status
code 2. -help may also be passed with two hyphens (--help). Both -help and -h
may be passed with DOS-style /h or /help flags.
EXAMPLES
Open original files in vim:
> recover-vim
List original files that have swap files:
> recover-vim ls -1
Pretty-print a list of original files:
> recover-vim printf '* %s\n'
Print this usage text:
> recover-vim -h
USAGE
exit 2
;;
esac
if [ $# -eq 0 ]; then
set -- vim
fi
# Find things that look like vim swap files
files=(`
find . -iname '.*.s[a-z][a-z]' |
sed -e 's@/\.\(.*\)\.s[a-z][a-z]$@/\1@' |
tr -s '\n' '\0' |
xargs -0 bash -c 'printf "%q\n" "$@"' _
`)
# Ensure all the files exist -- prefix them with a dot if we've accidentally
# stripped the original file's dot (vim won't create a ..foo.swp)
found=()
for ((i=0; i < "${#files[@]}"; i++)); do
f="${files[$i]}"
fdot="$(dirname "$f")/.$(basename "$f")"
if [ -f "$f" ]; then
found["${#found[@]}"]="$f"
elif [ -f "$fdot" ]; then
found["${#found[@]}"]="$fdot"
fi
done
unset files
if [ "${#found[@]}" -eq 0 ]; then
if [ -t 1 ]; then
echo "recover-vim: no swap files found" 1>&2
fi
exit 0
fi
exec "$@" "${found[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment