我如何在bash文件的绝对路径? [英] How do I get the absolute directory of a file in bash?
问题描述
我已经写了一个bash脚本,需要输入文件作为参数,并读取它。结果
该文件包含一些(相对于它的位置),以使用其他文件路径。
I have written a bash script that takes an input file as an argument and reads it.
This file contains some paths (relative to its location) to additional files used.
我想剧本去包含输入文件的文件夹,执行进一步的命令。
I would like the script to go to the folder containing the input file, to execute further commands.
因此,如何从一个输入文件中获取的文件夹(和公正的文件夹)?(在Linux上。)
So, how do I get the folder (and just the folder) from an input file? (In linux.)
推荐答案
要得到完整路径使用:
readlink -f relative/path/to/file
要获取文件的目录:
dirname relative/path/to/file
您也可以将二者结合起来:
You can also combine the two:
dirname $(readlink -f relative/path/to/file)
如果的readlink -f
不可用您的系统上,您可以使用这样的:
If readlink -f
is not available on your system you can use this:
function myreadlink() {
(
cd $(dirname $1) # or cd ${1%/*}
echo $PWD/$(basename $1) # or echo $PWD/${1##*/}
)
}
请注意,如果你只需要移动到指定为相对路径的文件的目录,你不需要知道的绝对路径,相对路径是完全合法的,所以只需使用:
Note that if you only need to move to a directory of a file specified as a relative path, you don't need to know the absolute path, a relative path is perfectly legal, so just use:
cd $(dirname relative/path/to/file)
如果你想回去(在脚本运行时)到原来的路径,使用 PUSHD
而不是 CD
和 POPD
当你完成。
if you wish to go back (while the script is running) to the original path, use pushd
instead of cd
, and popd
when you are done.
这篇关于我如何在bash文件的绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!