我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
当前回答
最高答案在所有情况下都没有工作......
因此,让我们看看一个例子,这些替代的解决方案,为描述的任务,询问到一个特定的文件的真正绝对路径:
PATH_TO_SCRIPT=`realpath -s $0`
PATH_TO_SCRIPT_DIR=`dirname $PATH_TO_SCRIPT`
但最好你应该使用这个先进的版本,也支持使用路径与空间(或可能甚至一些其他特殊的字符):
PATH_TO_SCRIPT=`realpath -s "$0"`
PATH_TO_SCRIPT_DIR=`dirname "$PATH_TO_SCRIPT"`
其他回答
您可以从脚本本身中获取一个Bash脚本的源目录,随之而来:
script_path=$(dirname "$(readlink -f "$0")")"/"
echo "$script_path"
样品输出:
/home/username/desktop/
使用“0”字母:
#!/usr/bin/env bash
echo "The script you are running has basename $( basename -- "$0"; ), dirname $( dirname -- "$0"; )";
echo "The present working directory is $( pwd; )";
使用 pwd 单独不会工作,如果您不从它包含的目录中运行脚本。
[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
好吧,如果在路上,字母和字母只是不会切断它,走路是艰难的(如果父母没有出口PATH?!)。
然而,盾牌必须对其脚本有一个开放的手稿,而在Bash手稿是#255。
SELF=`readlink /proc/$$/fd/255`
为我工作。
下面是易于记住的脚本:
DIR="$( dirname -- "${BASH_SOURCE[0]}"; )"; # Get the directory name
DIR="$( realpath -e -- "$DIR"; )"; # Resolve its full path if need be
最高答案在所有情况下都没有工作......
因此,让我们看看一个例子,这些替代的解决方案,为描述的任务,询问到一个特定的文件的真正绝对路径:
PATH_TO_SCRIPT=`realpath -s $0`
PATH_TO_SCRIPT_DIR=`dirname $PATH_TO_SCRIPT`
但最好你应该使用这个先进的版本,也支持使用路径与空间(或可能甚至一些其他特殊的字符):
PATH_TO_SCRIPT=`realpath -s "$0"`
PATH_TO_SCRIPT_DIR=`dirname "$PATH_TO_SCRIPT"`