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
23  # variables indicated by the caller.
24
25  # Description of argument(s):
26  # program_path_var                The name of the variable to receive the
27  #                                 program path.
28  # program_name_var                The name of the variable to receive the
29  #                                 program name.
30  # program_dir_path_var            The name of the variable to receive the
31  #                                 program dir path.
32  # follow_links                    If the program running is actually a link
33  #                                 to another file, use that file when
34  #                                 calculating the above values.
35
36  local _spn_loc_program_path_="${0}"
37
38  # The program name is the program path minus all characters up to and
39  # including the first slash.
40  local _spn_loc_program_name_=${_spn_loc_program_path_##*/}
41  # The program dir path is the program path minus everything from the last
42  # slash to the end of the string.
43  local _spn_loc_program_dir_path_=${_spn_loc_program_path_%${_spn_loc_program_name_}}
44
45  # If program dir path does not start with a slash then it is relative.
46  # Convert it to absolute.
47  if [ "${_spn_loc_program_dir_path_:0:1}" != "/" ] ; then
48    _spn_loc_program_dir_path_="$(readlink -f ${_spn_loc_program_dir_path_})/"
49    # Re-assemble the parts into program path variable.
50    _spn_loc_program_path_="${_spn_loc_program_dir_path_}${_spn_loc_program_name_}"
51  fi
52
53  if (( follow_links )) ; then
54    _spn_loc_program_path_=$(readlink -f ${_spn_loc_program_path_})
55    # Re-calculate program_name in case it is different now.
56    _spn_loc_program_name_=${_spn_loc_program_path_##*/}
57  fi
58
59  # Set caller's variables.
60  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_}\""
61  eval "${cmd_buf}"
62
63}
64