#!/usr/bin/env -iS HOME=${HOME} bash
# http://www.etalabs.net/sh_tricks.html

expand_tilde() {
    tilde_less="${1#\~/}"
    [ "$1" != "$tilde_less" ] && tilde_less="$HOME/$tilde_less"
    printf '%s' "$tilde_less"
}

test_start() 
{
  # home dir test
  if [ ~ != ${HOME} ]; then
    echo "Tilde expansion ('" ~ "') differs HOME ('${HOME}') .. exit"
    exit 1
  fi

  # tilde is not expanded in string as defined by POSIX https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_01
  echo "Tilde expansion in string                  : ~/.ssh"
  # tilde is expanded in string with custom function
  echo "Tilde expansion in string w/ expand_tilde():" $(expand_tilde "~/.ssh")
  # tilde is expanded when put before string
  echo "Tilde expansion before string              :" ~/".ssh"
  # do the same with $HOME
  echo "Content of home variable                   : ${HOME}/.ssh"

  # tilde expansion in tests
  touch ~/.tilde_expansion

  if [ -f "~/.tilde_expansion" ]; then
    echo "Unexpected success testing tilde expansion in string :O"
  else
    echo "Testing tilde expansion in string failed as expected ;)"
  fi

  if [ -f ~/".tilde_expansion" ]; then
    echo "Testing tilde expansion succeeds as expected ;)"
  else
    echo "Unexpected failure testing tilde expansion :O"
  fi

  if [ -f $(expand_tilde "~/.tilde_expansion") ]; then
    echo "Testing tilde expansion succeeds as expected ;)"
  else
    echo "Unexpected failure testing tilde expansion :O"
  fi

  rm ~/.tilde_expansion
}

test_start "$@"