Getting the source directory of a Bash script from

2018-12-30 23:48发布

How do I get the path of the directory in which a Bash script is located, inside that script?

For instance, let's say I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

30条回答
宁负流年不负卿
2楼-- · 2018-12-31 00:17

This is Linux specific, but you could use:

SELF=$(readlink /proc/$$/fd/255)
查看更多
只靠听说
3楼-- · 2018-12-31 00:18

For systems having GNU coreutils readlink (eg. linux):

$(readlink -f "$(dirname "$0")")

No need to use BASH_SOURCE when $0 contains the script filename.

查看更多
ら面具成の殇う
4楼-- · 2018-12-31 00:20

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

查看更多
春风洒进眼中
5楼-- · 2018-12-31 00:20

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

查看更多
不流泪的眼
6楼-- · 2018-12-31 00:22

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?

查看更多
忆尘夕之涩
7楼-- · 2018-12-31 00:22

Here is a POSIX compliant one-liner:

SCRIPT_PATH=`dirname "$0"`; SCRIPT_PATH=`eval "cd \"$SCRIPT_PATH\" && pwd"`

# test
echo $SCRIPT_PATH
查看更多
登录 后发表回答