如何在Linux shell脚本的命令行中从“../”获取完整路径

时间:2023-01-24 13:19:41

If I have a shell script where I get the parent folder using "../" can I expand that out somehow into it's absolute path?

如果我有一个shell脚本,我使用“../”获取父文件夹,我可以将它扩展到它的绝对路径吗?

4 个解决方案

#1


25  

You want readlink -f.

你想要readlink -f。

$ cd /tmp
$ readlink -f ..
/

#2


4  

Use realpath

使用realpath

$ realpath ..
/home

#3


1  

While you can often get the full path of a directory using stat, you can also use pwd -P ... however, it isn't much help unless you actually cd to the directory you are interested in.

虽然您通常可以使用stat获取目录的完整路径,但您也可以使用pwd -P ...但是,除非您实际上cd到您感兴趣的目录,否则它没有多大帮助。

To get around this limitation without actually changing the current working directory, I've found it fine to just run that cd in a sub-shell, as in:

为了解决这个限制而不实际更改当前工作目录,我发现在子shell中运行该CD很好,如:

THIS=`dirname $0`     # Which is often "."
PARENT=$(
  cd $THIS            # At this point, we are sure we're in script's directory
  dirname `pwd -P`
)
echo "PARENT=$PARENT"

#4


0  

When using in cmd line:

在cmd行中使用时:

dirname $(pwd)

When using in shell script:

在shell脚本中使用时:

PROJ_DIR=$(dirname $(pwd))

#1


25  

You want readlink -f.

你想要readlink -f。

$ cd /tmp
$ readlink -f ..
/

#2


4  

Use realpath

使用realpath

$ realpath ..
/home

#3


1  

While you can often get the full path of a directory using stat, you can also use pwd -P ... however, it isn't much help unless you actually cd to the directory you are interested in.

虽然您通常可以使用stat获取目录的完整路径,但您也可以使用pwd -P ...但是,除非您实际上cd到您感兴趣的目录,否则它没有多大帮助。

To get around this limitation without actually changing the current working directory, I've found it fine to just run that cd in a sub-shell, as in:

为了解决这个限制而不实际更改当前工作目录,我发现在子shell中运行该CD很好,如:

THIS=`dirname $0`     # Which is often "."
PARENT=$(
  cd $THIS            # At this point, we are sure we're in script's directory
  dirname `pwd -P`
)
echo "PARENT=$PARENT"

#4


0  

When using in cmd line:

在cmd行中使用时:

dirname $(pwd)

When using in shell script:

在shell脚本中使用时:

PROJ_DIR=$(dirname $(pwd))