Skip to content

Instantly share code, notes, and snippets.

@betafcc
Created March 14, 2019 09:45
Show Gist options
  • Save betafcc/f9848483005058f877a7584df8f5a8b4 to your computer and use it in GitHub Desktop.
Save betafcc/f9848483005058f877a7584df8f5a8b4 to your computer and use it in GitHub Desktop.
Pure bash equivalent to python's os.path.commonpath
#!/usr/bin/env bash
# takes paths in argv, assumes they are in absolute, as if it was outputed by `pwd`
common_path() {
if [ "$(printf '%s\n' "${@}" | sort | uniq | wc -l)" -eq 1 ]; then
printf %s "${1}"
return
fi
local n=2
while [ "$(printf '%s\n' "${@}" | cut -f-"${n}" -d'/' | sort | uniq | wc -l)" -eq 1 ]; do
if [ ${n} -gt 8 ]; then
break
fi
n=$((n + 1))
done
local result="$(printf '%s' "${1}" | cut -f-$((n - 1)) -d'/')"
if [ -z "${result}" ]; then
printf '/'
else
printf %s "${result}"
fi
}
common_path "${@}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment