brianonn
5/1/2017 - 5:58 AM

shell function for tilde expansion in a shell script. Works on Linux and OS X

shell function for tilde expansion in a shell script. Works on Linux and OS X

#########################################
# pathname tilde expansion
# supports ~ ~/path and ~user only
# ~+ ~- and digits are not supported and
# doesn't make sense in a script anyways
# Author: Brian A. Onn
# Date: Mon  1 May 2017 06:06:43 UTC
#########################################
expandpath () {
  local path="$1"
  local homedir expath user rest
  case "${path}" in
    '~') expath="${HOME}" ;;
    '~'/*) expath="${HOME}/${path##'~/'}" ;;
    '~'*) user=${path%%/*}; rest=${path##$user}; user=${user##'~'}
          if [ -x /usr/bin/dscacheutil ]; then    ## OS X
            set 1 $(dscacheutil -q user -a name "${user}" | grep -e '^dir:')
            homedir="$3"
          else
            IFS=: set 1 $(getent passwd "${user}")  ## Linux
            homedir="$7"
          fi
          [ -z "${homedir}" ] && expath="${path}" || expath="${homedir}${rest}"
          ;;
    *) expath="${path}" ;;
  esac
  echo "${expath}"
}