Skip to content

Instantly share code, notes, and snippets.

@divoxx
Last active November 26, 2018 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divoxx/ed26fed1d495d9a8d5c3cb3d32c688d2 to your computer and use it in GitHub Desktop.
Save divoxx/ed26fed1d495d9a8d5c3cb3d32c688d2 to your computer and use it in GitHub Desktop.
Bash function to tell if a path is writeable by current user
_is_writeable() {
if [[ "$(uname)" == "Darwin" ]]; then
mapfile -d $' ' -t stat < <(stat -L -f '%p %g %u' "${1}")
else
mapfile -d $' ' -t stat < <(stat -L -c '%a %g %u' "${1}")
fi
declare -i prm=${stat[0]}
declare -i grp=${stat[1]}
declare -i own=${stat[2]}
mapfile -t prm_words < <(echo "${prm}" | fold -w1)
declare -i prm_other=${prm_words[-1]}
declare -i prm_group=${prm_words[-2]}
declare -i prm_owner=${prm_words[-3]}
# Is writeable by others
if (( prm_other & 1<<1 )); then
return 0
# Is writeable by group
elif (( prm_group & 1<<1 )); then
mapfile -t groups < <(id -G)
for g in "${groups[@]}"; do
if (( g == grp )); then
return 0;
fi
done
# Is writeable by owner
elif (( prm_owner & 1<<1 )); then
declare -i user
user=$(id -u)
if [[ "${user}" == "${own}" ]]; then
return 0;
fi
fi
return 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment