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

查看:20
本文介绍了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天全站免登陆