与OSX bash脚本绝对路径 [英] Bash script absolute path with OSX

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

问题描述

我想获得OS X到当前正在运行的脚本的绝对路径。

I am trying to obtain the absolute path to the currently running script on OS X.

我看到了许多回复去为的readlink -f $ 1,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).

对于开箱解决方案的这个有什么建议?

Any suggestions for an out of the box solution to this?

推荐答案

有一个的真实路径() 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"

这逐字打印路径,如果它以 / 开始。如果不是它必须是一个相对路径,所以prepends $ 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.

这篇关于与OSX bash脚本绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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