OS X的Bash脚本绝对路径 [英] Bash script absolute path with OS X
问题描述
我正在尝试获取OS X上当前正在运行的脚本的绝对路径.
I am trying to obtain the absolute path to the currently running script on OS X.
我看到许多对readlink -f $0
的回复.但是,由于OS X的readlink
与BSD的相同,所以它根本不起作用(它可以与GNU的版本一起使用).
I saw many replies going for readlink -f $0
. However since OS X's readlink
is the same as BSD's, it just doesn't work (it works with GNU's version).
是否有现成的解决方案?
Is there an out-of-the-box solution to this?
推荐答案
有一个realpath()
C函数可以完成这项工作,但是我在命令行上看不到任何可用的东西.这是一个快速而肮脏的替代品:
There's a realpath()
C function that'll do the job, but I'm not seeing anything available on the command-line. Here's a quick and dirty replacement:
#!/bin/bash
realpath() {
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}
realpath "$0"
如果以/
开头,则逐字打印路径.如果不是,它必须是相对路径,因此它将$PWD
放在前面. #./
部分从$1
的前面剥离./
.
This prints the path verbatim if it begins with a /
. If not it must be a relative path, so it prepends $PWD
to the front. The #./
part strips off ./
from the front of $1
.
这篇关于OS X的Bash脚本绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!