diff --git a/documents/references.md b/documents/references.md index a779f9af0651656b2f52213a14485857bf6cab3e..1cbca98ab0bfd381e6bee5ce1bd4b9d1c5851ee6 100644 --- a/documents/references.md +++ b/documents/references.md @@ -39,6 +39,9 @@ Various references used in project. ### Check for Root User <https://stackoverflow.com/a/18216122> +### Get Absolute Directory +<https://stackoverflow.com/a/21188136> + ### Text Manipulation #### Change Output Color <https://stackoverflow.com/a/5947802> diff --git a/utils.sh b/utils.sh index 0e13cc54e6a3b196dc6213a4ad8396d4e26f5575..2bee1143538c7c810bed3ab2c69aedad4d57c879 100755 --- a/utils.sh +++ b/utils.sh @@ -27,6 +27,58 @@ return_value="" #endregion Global Utility Variables +#region Directory Functions + +### + # Gets absolute path of passed location. + ## +function get_absolute_path () { + + # Check number of passed function args. + if [[ ${#} == 1 ]] + then + # Expected number of args passed. Continue. + + # Check location type. + if [[ -f ${1} ]] + then + # Handle for file. + return_value="$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")" + + elif [[ -d ${1} ]] + then + # Handle for directory. + + # Extra logic to properly handle values of "./" and "../". + local current_dir="$(pwd)" + cd ${1} + + # Then call this to have consistent symlink handling as files. + return_value="$(cd "$(dirname "$(pwd)")"; pwd -P)/$(basename "$(pwd)")" + + # Change back to original location once value is set. + cd ${current_dir} + else + echo -e "${text_red}Passed value ( ${1} ) is not a valid file or directory.${text_reset}" + exit 1 + fi + + # Handle for too many args. + elif [[ ${#} > 1 ]] + then + echo -e "${text_red}Too many args passed. Expected one arg, received ${#}.${text_reset}" + exit 1 + + # Handle for too few args. + else + echo -e "${text_red}Too few args passed. Expected one arg, received 0.${text_reset}" + exit 1 + fi +} + +#endregion Directory Functions + + #region User Check Functions ###