Bash: function converts relative file path to absolute

tags: bash path ubuntu

For converting relative path to absolute full path in scripts I use this simple function. Also it works with path which contain '~’.

##
# Get full file/directory path
#
# Examples:
#   full_path=$(get_full_path '/tmp');       # /tmp
#   full_path=$(get_full_path '~/..');       # /home
#   full_path=$(get_full_path '../../../');  # /home
#
# @param {String} $1 - relative path
# @returns {String} absolute path
#
function get_full_path {
    local user_home;
    local user_home_sed;
    local rel_path;
    local result;
    user_home="${HOME//\//\\\/}";
    user_home_sed="s#~#${user_home}#g";
    rel_path=$( echo "${1}" | sed "${user_home_sed}" );
    result=$( readlink -e "${rel_path}" );
    echo "${result}";
}

Usage example:

text="Enter path to applications folder:";
read -r -e -p "${text}" apps_path_user;
full_path=$(get_full_path "${apps_path_user}");

Download from Github.

Note: Tested on Ubuntu.

Comments: