bash 在 solaris 上规范化路径名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1245301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:06:44  来源:igfitidea点击:

canonicalize a path name on solaris

bashpathsolarissymlink

提问by A B

On a GNU system I would just use readlink -f $SOME_PATH, but Solaris doesn't have readlink.

在 GNU 系统上,我只会使用readlink -f $SOME_PATH,但 Solaris 没有 readlink。

I'd prefer something that works well in bash, but other programs are ok if needed.

我更喜欢在 bash 中运行良好的东西,但如果需要,其他程序也可以。

Edit:The best I've come up with so far uses cd and pwd, but requires some more hackery to deal with files and not just directories.

编辑:到目前为止我想出的最好的使用 cd 和 pwd,但需要更多的hackery来处理文件而不仅仅是目录。

cd -P "$*"
REAL_PATH=`pwd`

采纳答案by Sean Bright

Does thishelp? From the referenced page:

请问帮助?从参考页面:

Create a file called canonicalizewith these contents:

创建一个canonicalize包含以下内容的文件:

#!/bin/bash
cd -P -- "$(dirname -- "")" &&
printf '%s\n' "$(pwd -P)/$(basename -- "")"

Make the file executable:

使文件可执行:

chmod +x canonicalize`

And finally:

最后:

user@host$ canonicalize ./bash_profile

回答by Yavin5

Might be overkill, but this is OS portable, and does not need to find the dirname nor basename binaries first.. this one-liner works. Just pass in your filename where you see $origFile:

可能有点矫枉过正,但这是操作系统可移植的,不需要先找到目录名或基名二进制文件..这个单行工作。只需在您看到 $origFile 的地方传入您的文件名:

perl -e "use Cwd realpath; print realpath(\"$origFile\");"

perl -e "use Cwd realpath; print realpath(\"$origFile\");"

回答by Josh

#!/bin/bash

# Resolves a full path
# - alternative to "readlink -f", which is not available on solaris
canonicalpath() {
  if [ -d  ]; then
    pushd  > /dev/null 2>&1
    echo $PWD
  elif [ -f  ]; then
    pushd $(dirname ) > /dev/null 2>&1
    echo $PWD/$(basename )
  else
    echo "Invalid path "
  fi
  popd > /dev/null 2>&1
}