我编写了一个bash脚本,它将输入文件作为参数并读取它
我希望脚本转到包含输入文件的文件夹,以执行进一步的命令.
所以,how do I get the folder (and just the folder) from an input file?(在linux中)
我编写了一个bash脚本,它将输入文件作为参数并读取它
我希望脚本转到包含输入文件的文件夹,以执行进一步的命令.
所以,how do I get the folder (and just the folder) from an input file?(在linux中)
要获取完整路径,请使用:
readlink -f relative/path/to/file
要获取文件的目录,请执行以下操作:
dirname relative/path/to/file
您还可以将两者结合起来:
dirname $(readlink -f relative/path/to/file)
如果您的系统上没有readlink -f
,您可以使用此*:
function myreadlink() {
(
cd "$(dirname $1)" # or cd "${1%/*}"
echo "$PWD/$(basename $1)" # or echo "$PWD/${1##*/}"
)
}
请注意,如果只需要移动到指定为相对路径的文件目录,则无需知道绝对路径,相对路径完全合法,因此只需使用:
cd $(dirname relative/path/to/file)
如果希望返回(在脚本运行时)原始路径,请使用pushd
而不是cd
,完成后使用popd
.
*虽然在这个问题的背景下,上面的myreadlink
已经足够好了,但相对于上面建议的readlink
工具,它有一些局限性.例如,它没有正确地跟踪指向具有不同属性的文件的链接.