gpt4 book ai didi

shell - 带有 shell 脚本的 pwd 命令

转载 作者:行者123 更新时间:2023-12-04 11:58:19 28 4
gpt4 key购买 nike

我正在调用一个脚本如下

目录路径:/user/local/script/print_path.sh

var_path=`pwd`
echo $var_path

上面的脚本调用如下
目录路径:/user/local/callPscript/call.sh
`/user/local/script/print_path.sh`

我想要的输出如下:
/user/local/script/

但它给出了输出:
/user/local/callPscript/

即调用脚本的位置。如何使其进入脚本主目录路径?

最佳答案

经过几周的 Bash 编程,这已经成为标准解决方案:

directory=$(dirname -- $(readlink -fn -- "$0"))
$0是脚本的相对路径, readlink -f将其解析为绝对路径,然后 dirname从路径的末尾去除脚本文件名。

基于 completely safe find 的更安全的变体:
directoryx="$(dirname -- $(readlink -fn -- "$0"; echo x))"
directory="${directoryx%x}"

这对于任何文件名都应该是安全的 - $()结构删除字符串末尾的换行符,这就是 x 的原因在末尾。

关于shell - 带有 shell 脚本的 pwd 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5256823/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com