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