Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- None of the current solutions work if there are any newlines at the end of the directory name - They will be stripped by the command substitution. To work around this you can append a non-newline character inside the command substitution - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd && echo x)" - and remove it without a command substitution - DIR="${DIR%x}". – l0b0 Sep 24 '12 at 12:15
- 73
- @jpmc26 There are two very common situations: Accidents and sabotage. A script shouldn't fail in unpredictable ways just because someone, somewhere, did a mkdir $'\n'. – l0b0 Mar 28 '13 at 8:14
- 14
- anyone who lets people sabotage their system in that way shouldn't leave it up to bash to detect such problems... much less hire people capable of making that kind of mistake. I have never had, in the 25 years of using bash, seen this kind of thing happen anywhere.... this is why we have things like perl and practices such as taint checking (i will probably be flamed for saying that :) – osirisgothra Feb 5 '15 at 0:12
- 2
- @l0b0 Consider that you'd need the same protection on dirname, and that the directory could start with a - (e.g. --help). DIR=$(reldir=$(dirname -- "$0"; echo x); reldir=${reldir%?x}; cd -- "$reldir" && pwd && echo x); DIR=${DIR%?x}. Perhaps this is overkill? – Score_Under Apr 28 '15 at 17:46
- 43
- I stronly suggest to read this Bash FAQ about the subject. – Rany Albeg Wein Jan 30 '16 at 2:22
- show 14 more comments
- 55 Answers
- active oldest votes
- 1 2 next
- 5731
- #!/bin/bash
- DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
- is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
- It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
- #!/bin/bash
- SOURCE="${BASH_SOURCE[0]}"
- while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
- DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
- SOURCE="$(readlink "$SOURCE")"
- [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
- done
- DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
- This last one will work with any combination of aliases, source, bash -c, symlinks, etc.
- Beware: if you cd to a different directory before running this snippet, the result may be incorrect!
- Also, watch out for $CDPATH gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2 on Mac). Adding >/dev/null 2>&1 at the end of your cd command will take care of both possibilities.
- To understand how it works, try running this more verbose form:
- #!/bin/bash
- SOURCE="${BASH_SOURCE[0]}"
- while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
- TARGET="$(readlink "$SOURCE")"
- if [[ $TARGET == /* ]]; then
- echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
- SOURCE="$TARGET"
- else
- DIR="$( dirname "$SOURCE" )"
- echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
- SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
- fi
- done
- echo "SOURCE is '$SOURCE'"
- RDIR="$( dirname "$SOURCE" )"
- DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
- if [ "$DIR" != "$RDIR" ]; then
- echo "DIR '$RDIR' resolves to '$DIR'"
- fi
- echo "DIR is '$DIR'"
- And it will print something like:
- SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
- SOURCE is './sym2/scriptdir.sh'
- DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
- DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
- shareimprove this answer
- edited Dec 24 '18 at 7:25
- community wiki
- 24 revs, 18 users 34%
- Dave Dopson
- 22
- You can fuse this approach with the answer by user25866 to arrive at a solution that works with source <script> and bash <script>: DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)". – Dan Moulding Oct 19 '11 at 15:54
- 18
- Sometimes cd prints something to STDOUT! E.g., if your $CDPATH has .. To cover this case, use DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )" – user716468 Feb 3 '13 at 2:33
- 86
- Wait, so what is the final command to use? – Xeoncross Jun 5 '14 at 14:19
- 137
- This accepted answer is not ok, it doesn't work with symlinks and is overly complex. dirname $(readlink -f $0) is the right command. See gist.github.com/tvlooy/cbfbdb111a4ebad8b93e for a testcase – tvlooy Jun 9 '15 at 19:32
- 118
- @tvlooy IMO your answer isn't exactly OK as-is either, because it fails when there is a space in the path. In contrast to a newline character, this isn't unlikely or even uncommon. dirname "$(readlink -f "$0")" doesn't add complexity and is fair measure more robust for the minimal amount of trouble. – Adrian Günter Oct 28 '15 at 23:38
- show 57 more comments
- 742
- Use dirname "$0":
- #!/bin/bash
- echo "The script you are running has basename `basename "$0"`, dirname `dirname "$0"`"
- echo "The present working directory is `pwd`"
- using pwd alone will not work if you are not running the script from the directory it is contained in.
- [matt@server1 ~]$ pwd
- /home/matt
- [matt@server1 ~]$ ./test2.sh
- The script you are running has basename test2.sh, dirname .
- The present working directory is /home/matt
- [matt@server1 ~]$ cd /tmp
- [matt@server1 tmp]$ ~/test2.sh
- The script you are running has basename test2.sh, dirname /home/matt
- The present working directory is /tmp
- shareimprove this answer
- edited Mar 29 '18 at 22:51
- community wiki
- 4 revs, 4 users 77%
- matt b
- 23
- For portability beyond bash, $0 may not always be enough. You may need to substitute "type -p $0" to make this work if the command was found on the path. – Darron Oct 23 '08 at 20:15
- 7
- @Darron: you can only use type -p if the script is executable. This can also open a subtle hole if the script is executed using bash test2.sh and there is another script with the same name executable somewhere else. – D.Shawley Feb 5 '10 at 12:18
- 74
- @Darron: but since the question is tagged bash and the hash-bang line explicitly mentions /bin/bash I'd say it's pretty safe to depend on bashisms. – Joachim Sauer Jun 11 '10 at 12:56
- 21
- +1, but the problem with using dirname $0 is that if the directory is the current directory, you'll get .. That's fine unless you're going to change directories in the script and expect to use the path you got from dirname $0 as though it were absolute. To get the absolute path: pushd `dirname $0` > /dev/null, SCRIPTPATH=`pwd`, popd > /dev/null: pastie.org/1489386 (But surely there's a better way to expand that path?) – T.J. Crowder Jan 23 '11 at 10:30
- 6
- @T.J. Crowder I'm not sure sure dirname $0 is a problem if you assign it to a variable and then use it to launch a script like $dir/script.sh; I would imagine this is the use case for this type of thing 90% of the time. ./script.sh would work fine. – matt b Jan 24 '11 at 12:55
- show 11 more comments
- 410
- The dirname command is the most basic, simply parsing the path up to the filename off of the $0 (script name) variable:
- dirname "$0"
- But, as matt b pointed out, the path returned is different depending on how the script is called. pwd doesn't do the job because that only tells you what the current directory is, not what directory the script resides in. Additionally, if a symbolic link to a script is executed, you're going to get a (probably relative) path to where the link resides, not the actual script.
- Some others have mentioned the readlink command, but at its simplest, you can use:
- dirname "$(readlink -f "$0")"
- readlink will resolve the script path to an absolute path from the root of the filesystem. So, any paths containing single or double dots, tildes and/or symbolic links will be resolved to a full path.
- Here's a script demonstrating each of these, whatdir.sh:
- #!/bin/bash
- echo "pwd: `pwd`"
- echo "\$0: $0"
- echo "basename: `basename $0`"
- echo "dirname: `dirname $0`"
- echo "dirname/readlink: $(dirname $(readlink -f $0))"
- Running this script in my home dir, using a relative path:
- >>>$ ./whatdir.sh
- pwd: /Users/phatblat
- $0: ./whatdir.sh
- basename: whatdir.sh
- dirname: .
- dirname/readlink: /Users/phatblat
- Again, but using the full path to the script:
- >>>$ /Users/phatblat/whatdir.sh
- pwd: /Users/phatblat
- $0: /Users/phatblat/whatdir.sh
- basename: whatdir.sh
- dirname: /Users/phatblat
- dirname/readlink: /Users/phatblat
- Now changing directories:
- >>>$ cd /tmp
- >>>$ ~/whatdir.sh
- pwd: /tmp
- $0: /Users/phatblat/whatdir.sh
- basename: whatdir.sh
- dirname: /Users/phatblat
- dirname/readlink: /Users/phatblat
- And finally using a symbolic link to execute the script:
- >>>$ ln -s ~/whatdir.sh whatdirlink.sh
- >>>$ ./whatdirlink.sh
- pwd: /tmp
- $0: ./whatdirlink.sh
- basename: whatdirlink.sh
- dirname: .
- dirname/readlink: /Users/phatblat
- shareimprove this answer
- edited Jan 4 '17 at 16:33
- community wiki
- 5 revs, 4 users 91%
- phatblat
- 9
- readlink will not availabe in some platform in default installation. Try to avoid using it if you can – T.L Jan 11 '12 at 9:14
- 30
- be careful to quote everything to avoid whitespace issues: export SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" – Catskul Sep 17 '13 at 19:40
- 9
- In OSX Yosemite 10.10.1 -f is not recognised as an option to readlink. Using stat -f instead does the job. Thanks – cucu8 Nov 26 '14 at 9:29
- 5
- In OSX, there is greadlink, which is basically the readlink we are all familiar. Here is a platform independent version: dir=`greadlink -f ${BASH_SOURCE[0]} || readlink -f ${BASH_SOURCE[0]}` – robert Jan 14 '16 at 20:16
- 4
- Good call, @robert. FYI, greadlink can easily be installed through homebrew: brew install coreutils – phatblat Jan 15 '16 at 21:27
- show 4 more comments
- 174
- pushd . > /dev/null
- SCRIPT_PATH="${BASH_SOURCE[0]}"
- if ([ -h "${SCRIPT_PATH}" ]); then
- while([ -h "${SCRIPT_PATH}" ]); do cd `dirname "$SCRIPT_PATH"`;
- SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
- fi
- cd `dirname ${SCRIPT_PATH}` > /dev/null
- SCRIPT_PATH=`pwd`;
- popd > /dev/null
- Works for all versions,including
- when called via multple depth soft link,
- when the file it
- when script called by command "source" aka . (dot) operator.
- when arg $0 is modified from caller.
- "./script"
- "/full/path/to/script"
- "/some/path/../../another/path/script"
- "./some/folder/script"
- Alternatively, if the bash script itself is a relative symlink you want to follow it and return the full path of the linked-to script:
- pushd . > /dev/null
- SCRIPT_PATH="${BASH_SOURCE[0]}";
- if ([ -h "${SCRIPT_PATH}" ]) then
- while([ -h "${SCRIPT_PATH}" ]) do cd `dirname "$SCRIPT_PATH"`; SCRIPT_PATH=`readlink "${SCRIPT_PATH}"`; done
- fi
- cd `dirname ${SCRIPT_PATH}` > /dev/null
- SCRIPT_PATH=`pwd`;
- popd > /dev/null
- SCRIPT_PATH is given in full path, no matter how it is called.
- Just make sure you locate this at start of the script.
- This comment and code Copyleft, selectable license under the GPL2.0 or later or CC-SA 3.0 (CreativeCommons Share Alike) or later. (c) 2008. All rights reserved. No warranty of any kind. You have been warned.
- http://www.gnu.org/licenses/gpl-2.0.txt
- http://creativecommons.org/licenses/by-sa/3.0/
- 18eedfe1c99df68dc94d4a94712a71aaa8e1e9e36cacf421b9463dd2bbaa02906d0d6656
- shareimprove this answer
- edited May 17 '18 at 11:21
- community wiki
- 9 revs, 7 users 54%
- user25866
- 4
- Nice! Could be made shorter replacing "pushd[...] popd /dev/null" by SCRIPT_PATH=readlink -f $(dirname "${VIRTUAL_ENV}"); – e-satis Nov 29 '09 at 11:34
- 5
- And instead of using pushd ...; would not it be better to use $(cd dirname "${SCRIPT_PATH}" && pwd)? But anyway great script! – ovanes Aug 18 '10 at 10:16
- 9
- Isn't the if redundant? while is testing the same thing... – gatopeich Aug 5 '11 at 13:28
- 4
- It's dangerous for a script to cd out of its current directory in the hope of cding back again later: The script may not have permission to change directory back to the directory that was current when it was invoked. (Same goes for pushd/popd) – Adrian Pronk Nov 6 '12 at 1:15
- 6
- readlink -f is GNU-specific. BSD readlink does not have that option. – bren brightwell Jun 3 '14 at 16:48
- show 12 more comments
- 100
- Short answer:
- `dirname $0`
- or (preferably):
- $(dirname "$0")
- shareimprove this answer
- edited Apr 19 '17 at 6:59
- community wiki
- 7 revs, 7 users 37%
- Fabien
- 13
- It won't work if you source the script. "source my/script.sh" – Arunprasad Rajkumar Feb 5 '14 at 7:34
- 5
- then nothing will – vidstige Mar 3 '16 at 10:14
- I use this all the time in my bash scripts that automate stuff and often invoke other scripts in the same dir. I'd never use source on these and cd $(dirname $0) is easy to remember. – guaka Jan 3 '17 at 16:28
- works for /bin/sh – shadi May 29 '17 at 6:25
- 12
- @vidstige: ${BASH_SOURCE[0]} instead of $0 will work with source my/script.sh – Timothy Jones Sep 27 '17 at 6:48
- show 1 more comment
- 96
- You can use $BASH_SOURCE
- #!/bin/bash
- scriptdir=`dirname "$BASH_SOURCE"`
- Note that you need to use #!/bin/bash and not #!/bin/sh since its a bash extension
- shareimprove this answer
- edited Jun 17 '14 at 10:12
- community wiki
- 2 revs
- Mr Shark
- 9
- When I do ./foo/script, then $(dirname $BASH_SOURCE) is ./foo. – Till Oct 25 '10 at 17:06
- also works with source / . operator! – grosser Aug 11 '11 at 20:53
- add a comment
- 61
- This should do it:
- DIR=$(dirname "$(readlink -f "$0")")
- Works with symlinks and spaces in path. See man pages for dirname and readlink.
- Edit:
- From the comment track it seems not to work with Mac OS. I have no idea why that is. Any suggestions?
- shareimprove this answer
- edited Jul 29 '17 at 22:04
- community wiki
- 7 revs, 2 users 97%
- Simon Rigét
- 5
- with your solution, invoking the script like ./script.sh shows . instead of the full directory path – Bruno Negrão Zica Jun 14 '16 at 18:27
- 3
- There's no -f option for readlink on MacOS. Use stat instead. But still, it shows . if you are in 'this' dir. – Denis The Menace Nov 21 '16 at 9:55
- 1
- This is the best solution on Ubuntu 16.04 – fviktor Mar 19 '17 at 15:50
- 2
- But not on mac bash! – Yordan Georgiev Jul 28 '17 at 20:06
- add a comment
- 55
- pwd can be used to find the current working directory, and dirname to find the directory of a particular file (command that was run, is $0, so dirname $0 should give you the directory of the current script).
- However, dirname gives precisely the directory portion of the filename, which more likely than not is going to be relative to the current working directory. If your script needs to change directory for some reason, then the output from dirname becomes meaningless.
- I suggest the following:
- #!/bin/bash
- reldir=`dirname $0`
- cd $reldir
- directory=`pwd`
- echo "Directory is $directory"
- This way, you get an absolute, rather then relative directory.
- Since the script will be run in a separate bash instance, there is no need to restore the working directory afterwards, but if you do want to change back in your script for some reason, you can easily assign the value of pwd to a variable before you change directory, for future use.
- Although just
- cd `dirname $0`
- solves the specific scenario in the question, I find having the absolute path to more more useful generally.
- shareimprove this answer
- edited Apr 1 '16 at 15:23
- community wiki
- 3 revs, 2 users 94%
- SpoonMeiser
- 8
- You can do it all in one line like this: DIRECTORY=$(cd dirname $0 && pwd) – dogbane Oct 29 '08 at 8:38
- This doesn't work if the script sources another script and you want to know the name of the latter. – reinierpost Mar 28 '14 at 13:10
- add a comment
- 33
- I don't think this is as easy as others have made it out to be. pwd doesn't work, as the current dir is not necessarily the directory with the script. $0 doesn't always have the info either. Consider the following three ways to invoke a script.
- ./script
- /usr/bin/script
- script
- In the first and third ways $0 doesn't have the full path info. In the second and third, pwd do not work. The only way to get the dir in the third way would be to run through the path and find the file with the correct match. Basically the code would have to redo what the OS does.
- One way to do what you are asking would be to just hardcode the data in the /usr/share dir, and reference it by full path. Data shoudn't be in the /usr/bin dir anyway, so this is probably the thing to do.
- shareimprove this answer
- edited Dec 2 '11 at 14:56
- community wiki
- 2 revs, 2 users 83%
- Jim
- 9
- If you intend to disprove his comment, PROVE that a script CAN access where it's stored with a code example. – Richard Duerr Nov 18 '15 at 18:54
- add a comment
- 32
- SCRIPT_DIR=$( cd ${0%/*} && pwd -P )
- shareimprove this answer
- edited May 30 '13 at 11:28
- community wiki
- 2 revs, 2 users 67%
- P M
- This is way shorter than the chosen answer. And appears to work just as well. This deserves 1000 votes just so people do not overlook it. – Patrick Sep 19 '13 at 3:07
- 1
- As many of the previous answers explain in detail, neither $0 nor pwd are guaranteed to have the right information, depending on how the script is invoked. – IMSoP Sep 23 '13 at 16:51
- add a comment
- 28
- This gets the current working directory on Mac OS X 10.6.6:
- DIR=$(cd "$(dirname "$0")"; pwd)
- shareimprove this answer
- edited Dec 3 '12 at 13:29
- community wiki
- 2 revs, 2 users 89%
- Pubguy
- add a comment
- 27
- $(dirname "$(readlink -f "$BASH_SOURCE")")
- shareimprove this answer
- edited May 13 '18 at 4:36
- community wiki
- 3 revs, 3 users 55%
- test11
- add a comment
- 26
- This is Linux specific, but you could use:
- SELF=$(readlink /proc/$$/fd/255)
- shareimprove this answer
- edited Dec 22 '13 at 0:07
- community wiki
- 3 revs, 3 users 75%
- Steve Baker
- 1
- It's also bash specific, but perhaps bash's behavior has changed? /proc/fd/$$/255 seems to point to the tty, not to a directory. For example, in my current login shell, file descriptors 0, 1, 2, and 255 all refer to /dev/pts/4. In any case, the bash manual doesn't mention fd 255, so it's probably unwise to depend on this behavior.\ – Keith Thompson Mar 29 '15 at 0:17
- 2
- Interactive shell != script. Anyway realpath ${BASH_SOURCE[0]}; would seem to be the best way to go. – Steve Baker Apr 6 '15 at 12:52
- add a comment
- 21
- Here is a POSIX compliant one-liner:
- SCRIPT_PATH=`dirname "$0"`; SCRIPT_PATH=`eval "cd \"$SCRIPT_PATH\" && pwd"`
- # test
- echo $SCRIPT_PATH
- shareimprove this answer
- edited Apr 15 '13 at 7:28
- community wiki
- 2 revs, 2 users 91%
- lamawithonel
- 3
- I had success with this when running a script by itself or by using sudo, but not when calling source ./script.sh – Michael R Apr 17 '13 at 21:57
- And it fails when cd is configured to print the new path name. – Aaron Digulla Nov 4 '13 at 13:45
- add a comment
- 16
- I tried every one of these and none of them worked. One was very close but had a tiny bug that broke it badly; they forgot to wrap the path in quotation marks.
- Also a lot of people assume you're running the script from a shell so forget when you open a new script it defaults to your home.
- Try this directory on for size:
- /var/No one/Thought/About Spaces Being/In a Directory/Name/And Here's your file.text
- This gets it right regardless how or where you run it.
- #!/bin/bash
- echo "pwd: `pwd`"
- echo "\$0: $0"
- echo "basename: `basename "$0"`"
- echo "dirname: `dirname "$0"`"
- So to make it actually useful here's how to change to the directory of the running script:
- cd "`dirname "$0"`"
- Hope that helps
- shareimprove this answer
- edited Feb 6 '11 at 2:04
- community wiki
- 4 revs
- Mike Bethany
- 3
- Doesn't work if the script is being sourced from another script. – reinierpost Mar 28 '14 at 13:12
- add a comment
- 16
- Here is the simple, correct way:
- actual_path=$(readlink -f "${BASH_SOURCE[0]}")
- script_dir=$(dirname "$actual_path")
- Explanation:
- ${BASH_SOURCE[0]} - the full path to the script. The value of this will be correct even when the script is being sourced, e.g. source <(echo 'echo $0') prints bash, while replacing it with ${BASH_SOURCE[0]} will print the full path of the script. (Of course, this assumes you're OK taking a dependency on Bash.)
- readlink -f - Recursively resolves any symlinks in the specified path. This is a GNU extension, and not available on (for example) BSD systems. If you're running a Mac, you can use Homebrew to install GNU coreutils and supplant this with greadlink -f.
- And of course dirname gets the parent directory of the path.
- shareimprove this answer
- edited Feb 20 '16 at 7:53
- community wiki
- 2 revs
- James Ko
- SCRIPT_DIR=$(dirname $(readlink -f "${BASH_SOURCE[0]}")) – isapir Oct 31 '18 at 18:19
- add a comment
- 16
- I am tired of coming to this page over and over to copy paste the one-liner in the accepted answer. The problem with that is it is not easy to understand and remember.
- Here is an easy-to-remember script:
- DIR=$(dirname "${BASH_SOURCE[0]}") # get the directory name
- DIR=$(realpath "${DIR}") # resolve its full path if need be
- shareimprove this answer
- answered Nov 7 '18 at 4:30
- community wiki
- Thamme Gowda
- realpath comes from GNU coreutils, but does anyone know how common it is across other dists? – conny Mar 15 at 9:09
- add a comment
- 15
- I would use something like this:
- # retrieve the full pathname of the called script
- scriptPath=$(which $0)
- # check whether the path is a link or not
- if [ -L $scriptPath ]; then
- # it is a link then retrieve the target path and get the directory name
- sourceDir=$(dirname $(readlink -f $scriptPath))
- else
- # otherwise just get the directory name of the script path
- sourceDir=$(dirname $scriptPath)
- fi
- shareimprove this answer
- answered Nov 21 '12 at 3:57
- community wiki
- Nicolas
- This is the real one! Works with simple sh too! Problem with simple dirname "$0" based solutions: If the script is in the $PATH and is invoked without path, they will give wrong result. – Notinlist Nov 18 '14 at 10:25
- @Notinlist Not so. If the script is found via the PATH, $0 will contain the absolute filename. If the script is invoked with a relative or absolute filename containing a /, $0 will contain that. – Neil Mayhew Feb 3 '16 at 22:08
- add a comment
- 14
- A slight revision to the solution e-satis and 3bcdnlklvc04a pointed out in their answer
- SCRIPT_DIR=''
- pushd "$(dirname "$(readlink -f "$BASH_SOURCE")")" > /dev/null && {
- SCRIPT_DIR="$PWD"
- popd > /dev/null
- }
- This should still work in all the cases they listed.
- EDIT: prevent popd after failed pushd, thanks to konsolebox
- shareimprove this answer
- edited May 23 '17 at 10:31
- community wiki
- 3 revs
- Fuwjax
- This works perfectly to get the "real" dirname, rather than just the name of a symlink. Thank you! – Jay Taylor Jun 23 '10 at 20:32
- 1
- Better SCRIPT_DIR=''; pushd "$(dirname "$(readlink -f "$BASH_SOURCE")")" > /dev/null && { SCRIPT_DIR=$PWD; popd > /dev/null; } – konsolebox Jul 3 '14 at 4:15
- @konsolebox, what are you trying to defend against? I'm generally a fan of inlining logical conditionals, but what was the specific error that you were seeing in the pushd? I'd match rather find a way to handle it directly instead of returning an empty SCRIPT_DIR. – Fuwjax Jan 19 '15 at 20:03
- @Fuwjax Natural practice to avoid doing popd in cases (even when rare) where pushd fails. And in case pushd fails, what do you think should be the value of SCRIPT_DIR? The action may vary depending on what may seem logical or what one user could prefer but certainly, doing popd is wrong. – konsolebox Jan 20 '15 at 19:21
- add a comment
- 13
- #!/bin/sh
- PRG="$0"
- # need this for relative symlinks
- while [ -h "$PRG" ] ; do
- PRG=`readlink "$PRG"`
- done
- scriptdir=`dirname "$PRG"`
- shareimprove this answer
- answered Sep 13 '08 at 1:28
- community wiki
- Monkeyboy
- add a comment
- 11
- $_ is worth mentioning as an alternative to $0. If you're running a script from bash, the accepted answer can be shortened to:
- DIR="$( dirname "$_" )"
- Note that this has to be the first statement in your script.
- shareimprove this answer
- answered Sep 16 '11 at 19:05
- community wiki
- hurrymaplelad
- 3
- It breaks if you source or . the script. In those situations, $_ would contain the last parameter of the last command you ran before the .. $BASH_SOURCE works every time. – clacke Jan 31 '14 at 14:55
- add a comment
- 11
- I've compared many of the answers given, and come up with some more compact solutions. These seem to handle all of the crazy edge cases that arise from your favorite combination of:
- Absolute paths or relative paths
- File and directory soft links
- Invocation as script, bash script, bash -c script, source script, or . script
- Spaces, tabs, newlines, unicode, etc. in directories and/or filename
- Filenames beginning with a hyphen
- If you're running from Linux, it seems that using the proc handle is the best solution to locate the fully resolved source of the currently running script (in an interactive session, the link points to the respective /dev/pts/X):
- resolved="$(readlink /proc/$$/fd/255 && echo X)" && resolved="${resolved%$'\nX'}"
- This has a small bit of ugliness to it, but the fix is compact and easy to understand. We aren't using bash primitives only, but I'm okay with that because readlink simplifies the task considerably. The echo X adds an X to the end of the variable string so that any trailing whitespace in the filename doesn't get eaten, and the parameter substitution ${VAR%X} at the end of the line gets rid of the X. Because readlink adds a newline of its own (which would normally be eaten in the command substitution if not for our previous trickery), we have to get rid of that, too. This is most easily accomplished using the $'' quoting scheme, which lets us use escape sequences such as \n to represent newlines (this is also how you can easily make deviously named directories and files).
- The above should cover your needs for locating the currently running script on Linux, but if you don't have the proc filesystem at your disposal, or if you're trying to locate the fully resolved path of some other file, then maybe you'll find the below code helpful. It's only a slight modification from the above one-liner. If you're playing around with strange directory/filenames, checking the output with both ls and readlink is informative, as ls will output "simplified" paths, substituting ? for things like newlines.
- absolute_path=$(readlink -e -- "${BASH_SOURCE[0]}" && echo x) && absolute_path=${absolute_path%?x}
- dir=$(dirname -- "$absolute_path" && echo x) && dir=${dir%?x}
- file=$(basename -- "$absolute_path" && echo x) && file=${file%?x}
- ls -l -- "$dir/$file"
- printf '$absolute_path: "%s"\n' "$absolute_path"
- shareimprove this answer
- edited Jul 25 '15 at 19:14
- community wiki
- 3 revs, 2 users 85%
- billyjmc
- I get /dev/pts/30 with bash on Ubuntu 14.10 Desktop. – Dan Dascalescu Aug 15 '15 at 11:29
- @DanDascalescu Using the one-liner? Or the full code snippet at the bottom? And were you feeding it any tricky pathnames? – billyjmc Aug 19 '15 at 6:34
- The one line plus another line to echo $resolved, I saved it as d, chmod +x d, ./d. – Dan Dascalescu Aug 20 '15 at 5:55
- @DanDascalescu The first line in your script needs to be #!/bin/bash – billyjmc Aug 23 '15 at 5:07
- @DanDascalescu See stackoverflow.com/a/12296783/558709 – billyjmc Aug 23 '15 at 5:17
- add a comment
- 10
- For systems having GNU coreutils readlink (eg. linux):
- $(readlink -f "$(dirname "$0")")
- No need to use BASH_SOURCE when $0 contains the script filename.
- shareimprove this answer
- edited May 13 '18 at 4:34
- community wiki
- 2 revs
- user1338062
- 1
- unless the script was sourced with . or 'source' in which case it will still be whatever script sourced it, or, if from the command line, '-bash' (tty login) or 'bash' (invoked via 'bash -l') or '/bin/bash' (invoked as an interactive non-login shell) – osirisgothra Feb 5 '15 at 0:07
- I added second pair of quotes around dirname call. Needed if the directory path contains spaces. – user1338062 May 13 '18 at 4:35
- add a comment
- 9
- Try using:
- real=$(realpath $(dirname $0))
- shareimprove this answer
- edited Feb 6 '12 at 11:20
- community wiki
- 2 revs, 2 users 60%
- eeerahul
- All I want to know is, why this way is not good? It seemed no bad and correct for me. Could anyone explain why it's downvoted? – Shou Ya Aug 28 '12 at 15:16
- 6
- realpath is not a standard utility. – Steve Bennett May 13 '13 at 12:06
- On Linux, realpath is a standard utility (part of the GNU coreutils package), but it is not a bash built-in (i.e., a function provided by bash itself). If you're running Linux, this method will probably work, although I'd substitute the $0 for ${BASH_SOURCE[0]} so that this method will work anywhere, including in a function. – Doug Richardson Jul 18 '14 at 15:53
- 2
- The order of the operations in this answer is wrong. You need to first resolve the symlink, then do dirname because the last part of $0 may be a symlink that points to a file that is not in the same directory as the symlink itself. The solution described in this answer just gets the path of the directory where the symlink it stored, not the directory of the target. Furthermore, this solution is missing quoting. It will not work if the path contains special characters. – hagello Apr 13 '15 at 21:43
- This solution "just gets the path of the directory where the symlink it stored", and that's what I actually want. PS: quoting still should be added. – Kostiantyn Ponomarenko Mar 11 at 10:19
- show 1 more comment
- 8
- So... I believe I've got this one. Late to the party, but I think some will appreciate it being here is them come across this thread. The comments should explain.
- #!/bin/sh # dash bash ksh # !zsh (issues). G. Nixon, 12/2013. Public domain.
- ## 'linkread' or 'fullpath' or (you choose) is a little tool to recursively
- ## dereference symbolic links (ala 'readlink') until the originating file
- ## is found. This is effectively the same function provided in stdlib.h as
- ## 'realpath' and on the command line in GNU 'readlink -f'.
- ## Neither of these tools, however, are particularly accessible on the many
- ## systems that do not have the GNU implementation of readlink, nor ship
- ## with a system compiler (not to mention the requisite knowledge of C).
- ## This script is written with portability and (to the extent possible, speed)
- ## in mind, hence the use of printf for echo and case statements where they
- ## can be substituded for test, though I've had to scale back a bit on that.
- ## It is (to the best of my knowledge) written in standard POSIX shell, and
- ## has been tested with bash-as-bin-sh, dash, and ksh93. zsh seems to have
- ## issues with it, though I'm not sure why; so probably best to avoid for now.
- ## Particularly useful (in fact, the reason I wrote this) is the fact that
- ## it can be used within a shell script to find the path of the script itself.
- ## (I am sure the shell knows this already; but most likely for the sake of
- ## security it is not made readily available. The implementation of "$0"
- ## specificies that the $0 must be the location of **last** symbolic link in
- ## a chain, or wherever it resides in the path.) This can be used for some
- ## ...interesting things, like self-duplicating and self-modifiying scripts.
- ## Currently supported are three errors: whether the file specified exists
- ## (ala ENOENT), whether its target exists/is accessible; and the special
- ## case of when a sybolic link references itself "foo -> foo": a common error
- ## for beginners, since 'ln' does not produce an error if the order of link
- ## and target are reversed on the command line. (See POSIX signal ELOOP.)
- ## It would probably be rather simple to write to use this as a basis for
- ## a pure shell implementation of the 'symlinks' util included with Linux.
- ## As an aside, the amount of code below **completely** belies the amount
- ## effort it took to get this right -- but I guess that's coding for you.
- ##===-------------------------------------------------------------------===##
- for argv; do :; done # Last parameter on command line, for options parsing.
- ## Error messages. Use functions so that we can sub in when the error occurs.
- recurses(){ printf "Self-referential:\n\t$argv ->\n\t$argv\n" ;}
- dangling(){ printf "Broken symlink:\n\t$argv ->\n\t"$(readlink "$argv")"\n" ;}
- errnoent(){ printf "No such file: "$@"\n" ;} # Borrow a horrible signal name.
- # Probably best not to install as 'pathfull', if you can avoid it.
- pathfull(){ cd "$(dirname "$@")"; link="$(readlink "$(basename "$@")")"
- ## 'test and 'ls' report different status for bad symlinks, so we use this.
- if [ ! -e "$@" ]; then if $(ls -d "$@" 2>/dev/null) 2>/dev/null; then
- errnoent 1>&2; exit 1; elif [ ! -e "$@" -a "$link" = "$@" ]; then
- recurses 1>&2; exit 1; elif [ ! -e "$@" ] && [ ! -z "$link" ]; then
- dangling 1>&2; exit 1; fi
- fi
- ## Not a link, but there might be one in the path, so 'cd' and 'pwd'.
- if [ -z "$link" ]; then if [ "$(dirname "$@" | cut -c1)" = '/' ]; then
- printf "$@\n"; exit 0; else printf "$(pwd)/$(basename "$@")\n"; fi; exit 0
- fi
- ## Walk the symlinks back to the origin. Calls itself recursivly as needed.
- while [ "$link" ]; do
- cd "$(dirname "$link")"; newlink="$(readlink "$(basename "$link")")"
- case "$newlink" in
- "$link") dangling 1>&2 && exit 1 ;;
- '') printf "$(pwd)/$(basename "$link")\n"; exit 0 ;;
- *) link="$newlink" && pathfull "$link" ;;
- esac
- done
- printf "$(pwd)/$(basename "$newlink")\n"
- }
- ## Demo. Install somewhere deep in the filesystem, then symlink somewhere
- ## else, symlink again (maybe with a different name) elsewhere, and link
- ## back into the directory you started in (or something.) The absolute path
- ## of the script will always be reported in the usage, along with "$0".
- if [ -z "$argv" ]; then scriptname="$(pathfull "$0")"
- # Yay ANSI l33t codes! Fancy.
- printf "\n\033[3mfrom/as: \033[4m$0\033[0m\n\n\033[1mUSAGE:\033[0m "
- printf "\033[4m$scriptname\033[24m [ link | file | dir ]\n\n "
- printf "Recursive readlink for the authoritative file, symlink after "
- printf "symlink.\n\n\n \033[4m$scriptname\033[24m\n\n "
- printf " From within an invocation of a script, locate the script's "
- printf "own file\n (no matter where it has been linked or "
- printf "from where it is being called).\n\n"
- else pathfull "$@"
- fi
- shareimprove this answer
- answered Dec 21 '13 at 17:47
- community wiki
- Geoff Nixon
- add a comment
- 8
- Try the following cross-compatible solution:
- CWD="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"
- as realpath or readlink commands are not always available (depending on the operating system) and ${BASH_SOURCE[0]} is available only in bash shell.
- Alternatively you can try the following function in bash:
- realpath () {
- [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
- }
- This function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWD variable + filename argument (without ./ prefix).
- Related:
- How to set current working directory to the directory of the script?
- Bash script absolute path with OSX
- Reliable way for a bash script to get the full path to itself?
- shareimprove this answer
- edited Apr 24 '15 at 2:23
- community wiki
- 4 revs
- kenorb
- Please explain more about the realpath function. – Chris Mar 27 '15 at 16:54
- 1
- @Chris realpath function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWD + filename (without ./ prefix). – kenorb Mar 27 '15 at 17:35
- Your cross-compatible solution doesn’t work when the script is symlinked. – Jakub Jirutka Sep 8 '15 at 20:59
- add a comment
- 7
- Hmm, if in the path basename & dirname are just not going to cut it and walking the path is hard (what if parent didn't export PATH!). However, the shell has to have an open handle to its script, and in bash the handle is #255.
- SELF=`readlink /proc/$$/fd/255`
- works for me.
- shareimprove this answer
- edited Jul 27 '11 at 20:17
- community wiki
- 2 revs, 2 users 86%
- Joshua
- I get /dev/pts/30 with bash on Ubuntu 14.10 Desktop, instead of the actual directory I run the script from. – Dan Dascalescu Aug 15 '15 at 11:30
- add a comment
- 6
- This works in bash-3.2:
- path="$( dirname "$( which "$0" )" )"
- Here's an example of its usage:
- Say you have a ~/bin directory, which is in your $PATH. You have script A inside this directory. It sources script ~/bin/lib/B. You know where the included script is relative to the original one (the subdirectory lib), but not where it is relative to the user's current directory.
- This is solved by the following (inside A):
- source "$( dirname "$( which "$0" )" )/lib/B"
- It doesn't matter where the user is or how he calls the script, this will always work.
- shareimprove this answer
- edited Sep 3 '10 at 6:44
- community wiki
- 5 revs, 2 users 97%
- Matt Tardiff
- 2
- The point on which is very debatable. type, hash, and other builtins do the same thing better in bash. which is kindof more portable, though it really isn't the same which used in other shells like tcsh, that has it as a builtin. – BroSlow Jan 13 '14 at 22:30
- "Always"? Not at all. which being an external tool, you have no reason to believe it behaves identically to the parent shell. – Charles Duffy Jun 9 '14 at 3:42
- add a comment
- 5
- None of these worked for a bash script launched by Finder in OS X - I ended up using:
- SCRIPT_LOC="`ps -p $$ | sed /PID/d | sed s:.*/Network/:/Network/: |
- sed s:.*/Volumes/:/Volumes/:`"
- Not pretty, but it gets the job done.
- shareimprove this answer
- edited Feb 14 '13 at 17:23
- community wiki
- 2 revs, 2 users 67%
- tigfox
- add a comment
- 5
- The best compact solution in my view would be:
- "$( cd "$( echo "${BASH_SOURCE[0]%/*}" )"; pwd )"
- There is no reliance on anything other than Bash. The use of dirname, readlink and basename will eventually lead to compatibility issues, so they are best avoided if at all possible.
- shareimprove this answer
- answered Oct 8 '13 at 14:24
- community wiki
- AsymLabs
- 1
- You probably should add slash to that: "$( cd "$( echo "${BASH_SOURCE[0]%/*}/" )"; pwd )". You'd have problems with root directory if you don't. Also why do you even have to use echo? – konsolebox Jul 2 '14 at 17:21
- dirname and basename are POSIX standardized, so why avoid using them? Links: dirname, basename – myrdd Oct 29 '18 at 9:18
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement