Skip to content

Instantly share code, notes, and snippets.

@SomajitDey
Last active September 26, 2021 16:11
Show Gist options
  • Save SomajitDey/103b1ece5f3e40eb5abbe375c7b256b4 to your computer and use it in GitHub Desktop.
Save SomajitDey/103b1ece5f3e40eb5abbe375c7b256b4 to your computer and use it in GitHub Desktop.
Bash function to transform any Unix/Windows path to absolute Unix path
abs_path(){
# Transforms any path, including windows paths, given as parameter, to absolute path.
# Expands ~, ~-, \ etc.
# Exitcode: 0 (output to stdout) if path exists, 1 (outout to stderr) otherwise.
local path="${1}"
# Windows to Unix path [if operand is Unix path, then wslpath outputs to stderr]
local buffer=$(wslpath -u "${path}" 2>/dev/null); path="${buffer:-"${path}"}"
eval path="${path}" # Remove backslash, Tilde expansion etc.
[[ "${path}" != /* ]] && path="${PWD}/${path}"
[[ -e "${path}" ]] && echo "${path}" && return 0
echo "${path}" >&2 && return 1
}
########################## Testing #######################
# Source this file as: . ./abs_path.bash
# Bash command: abs_path <drag-&-drop any file/directory from *nix/WSL/Windows here or type whatever you fancy>
# echo $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment