OS X的Bash脚本绝对路径 [英] Bash script absolute path with OS X

查看:76
本文介绍了OS X的Bash脚本绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆