假设我有这个简单的 bash 脚本:
#!/usr/bin/env bash
file="$1";
if [ -z "$file" ]; then
echo "Must pass relative file path as the first argument.";
fi
git_root=`git rev-parse --show-toplevel`;
# => need to resolve file from an absolute path to relative path, relative to git root
git diff HEAD:"$file" remotes/origin/dev:"$file"
如果我将绝对路径传递给该脚本,它需要能够处理它。做到这一点的规范方法是什么?要检查它是否是绝对文件路径,我们是否只检查第一个字符是否为“/”?
答案1
我使用的是 MacOS,所以我必须安装 coreutils:
brew install coreutils
然后我们可以像这样使用 realpath:
file=`realpath --relative-to="$git_root" "$file"`
或者,如果您需要无需安装任何东西即可运行的东西,您可以使用此 node.js 脚本:
#!/usr/bin/env node
'use strict';
const path = require('path');
const file = process.argv[2];
const relativeTo = process.argv[3];
if (!relativeTo) {
console.error('must pass an absolute path as the second argument.');
process.exit(1);
}
if (!file) {
console.error('must pass a file as the first argument.');
process.exit(1);
}
console.log(path.relative(relativeTo, file));