Created
March 14, 2019 09:45
-
-
Save betafcc/f9848483005058f877a7584df8f5a8b4 to your computer and use it in GitHub Desktop.
Pure bash equivalent to python's os.path.commonpath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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