1#!/bin/bash 2 3# Universal bash program setup functions. 4 5# Example usage: 6 7# Source files to get required functions. 8# source_files="gen_setup.sh" 9# source_file_paths=$(type -p ${source_files}) 10# for file_path in ${source_file_paths} ; do source ${file_path} ; done 11 12# Turn on extended globbing. 13shopt -s extglob 14 15 16function get_pgm_path_info() { 17 local program_path_var="${1:-program_path}" ; shift 18 local program_name_var="${1:-program_name}" ; shift 19 local program_dir_path_var="${1:-program_dir_path}" ; shift 20 local follow_links="${1:-0}" ; shift 21 22 # Determine the program path, name and dir path and assign them to the variables indicated by the caller. 23 24 # Description of argument(s): 25 # program_path_var The name of the variable to receive the program path. 26 # program_name_var The name of the variable to receive the program name. 27 # program_dir_path_var The name of the variable to receive the program dir path. 28 # follow_links If the program running is actually a link to another file, use that file 29 # when calculating the above values. 30 31 local _spn_loc_program_path_="${0}" 32 33 # The program name is the program path minus all characters up to and including the first slash. 34 local _spn_loc_program_name_=${_spn_loc_program_path_##*/} 35 # The program dir path is the program path minus everything from the last slash to the end of the string. 36 local _spn_loc_program_dir_path_=${_spn_loc_program_path_%${_spn_loc_program_name_}} 37 38 # If program dir path does not start with a slash then it is relative. Convert it to absolute. 39 if [ "${_spn_loc_program_dir_path_:0:1}" != "/" ] ; then 40 _spn_loc_program_dir_path_="$(readlink -f ${_spn_loc_program_dir_path_})/" 41 # Re-assemble the parts into program path variable. 42 _spn_loc_program_path_="${_spn_loc_program_dir_path_}${_spn_loc_program_name_}" 43 fi 44 45 if (( follow_links )) ; then 46 _spn_loc_program_path_=$(readlink -f ${_spn_loc_program_path_}) 47 # Re-calculate program_name in case it is different now. 48 _spn_loc_program_name_=${_spn_loc_program_path_##*/} 49 fi 50 51 # Set caller's variables. 52 cmd_buf="${program_path_var}=\"\${_spn_loc_program_path_}\" ; ${program_name_var}=\"\${_spn_loc_program_name_}\" ; ${program_dir_path_var}=\"\${_spn_loc_program_dir_path_}\"" 53 eval "${cmd_buf}" 54 55} 56