blob: 2aed0eaf8cf429535ed7fe9339353e98b5dd838a [file] [log] [blame]
Michael Walsh2c3d6ed2019-05-29 17:13:01 -05001#!/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
Michael Walsh410b1782019-10-22 15:56:18 -050022 # Determine the program path, name and dir path and assign them to the variables indicated by the caller.
Michael Walsh2c3d6ed2019-05-29 17:13:01 -050023
24 # Description of argument(s):
Michael Walsh410b1782019-10-22 15:56:18 -050025 # 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.
Michael Walsh2c3d6ed2019-05-29 17:13:01 -050030
31 local _spn_loc_program_path_="${0}"
32
Michael Walsh410b1782019-10-22 15:56:18 -050033 # The program name is the program path minus all characters up to and including the first slash.
Michael Walsh2c3d6ed2019-05-29 17:13:01 -050034 local _spn_loc_program_name_=${_spn_loc_program_path_##*/}
George Keishing4f5eb802019-10-25 11:29:32 -050035 # The program dir path is the program path minus everything from the last slash to the end of the string.
Michael Walsh2c3d6ed2019-05-29 17:13:01 -050036 local _spn_loc_program_dir_path_=${_spn_loc_program_path_%${_spn_loc_program_name_}}
37
Michael Walsh410b1782019-10-22 15:56:18 -050038 # If program dir path does not start with a slash then it is relative. Convert it to absolute.
Michael Walsh2c3d6ed2019-05-29 17:13:01 -050039 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}