$( dirname "${BASH_SOURCE[0]}" )
如果您从同一目录调用脚本,则返回.
;如果您使用相对路径(例如../myscript.sh
.
I use script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
to get the directory that the script is in.
Here's an example script to test this functionality:
#!/bin/bash
# This script is located at /home/lrobert/test.sh
# This just tests the current PWD
echo "PWD: $(pwd)"
# Using just bash source returns the relative path to the script
# If called from /home with the command 'lrobert/test.sh' this returns 'lrobert'
bash_source="$(dirname "${BASH_SOURCE[0]}")"
echo "bash_source: ${bash_source}"
# This returns the actual path to the script
# Returns /home/lrobert when called from any directory
script_dir=$( cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
echo "script_dir: ${script_dir}"
# This just tests to see if our PWD was modified
echo "PWD: $(pwd)"