blob: 85559c88ace18f5cf03b68741b0bdc80e5198737 (
plain)
1 Finding the Absolute Path of a Bash Script
2 ==========================================
3 :author: Aaron Ball
4 :email: nullspoon@iohq.net
5
6
7
8 This seems to be one that a lot of people want to know how to do (I was one of
9 them). In searching the internets I found a lot of suggestions to use the
10 _readline_ external command. I need to have the script that uses this work on
11 Linux and AIX though, which means readline and many other external commands
12 will not be available to me. Here's how it can be done in bash
13
14 ----
15 #
16 # Determines the absolute path to the running script. This is useful for
17 # needing to muck around in the running directory when the script has been
18 # called using a relative path
19 #
20 getScriptAbsolutePath() {
21 if [[ ${0:0:1} == '/' ]]; then
22 # If the script was called absolutely
23 absPath=${0}
24 else
25 # If the script was called relatively, strip the . off the front
26 script=`echo ${0} | sed 's/\.\?\(.*\)$/\1/'`
27 absPath="$(pwd)/${script}"
28 fi
29 # Strip the script filename off the end
30 absPath=`echo ${absPath} | sed 's/\(.*\/\).*\$/\1/'`
31 }
32 ----
33
34 So what we do here is start with two variables: The working directory (output
35 of pwd), and command used to call the script ($0). The command used to call the
36 script could be anything like
37
38 * +./blah.sh+
39 * +./scripts/blah/blah.sh+
40 * +/usr/local/res/scripts/blah/blah.sh+
41
42 If argument 0 starts with a / (such as /usr/local/res/scripts/blah/blah.sh),
43 the script was called using an absolute path, so we can just use $0 as our
44 absolute path once we strip the script name off the end.
45
46 If otherwise, the script was called using a relative path and $0 needs to be
47 appended to the output of pwd and to get the absolute path. Using sed, we strip
48 off the leading period if it exists as well as the script filename.
49
50
51 Category:Linux
52 Category:Bash
53 Category:Scripting
54
55
56 // vim: set syntax=asciidoc:
|