【发布时间】:2010-07-23 14:18:41
【问题描述】:
是否有一个等同于__FILE__ 的sh 来给我当前执行文件的路径名? POSIX 解决方案首选,bash 可接受,谢谢。
【问题讨论】:
是否有一个等同于__FILE__ 的sh 来给我当前执行文件的路径名? POSIX 解决方案首选,bash 可接受,谢谢。
【问题讨论】:
尝试使用$0。
【讨论】:
__FILE__。
这将同时获取文件和目录
# !/bin/sh
# store where we are
__PWD__=$(pwd)
# go to the current file (i.e. this file)
cd $(dirname $0)
# gives the file name, __FILE__
echo $0
__FILE__=$0
# gives the directory name, __DIR__
echo $(dirname $0)
__DIR__=$(dirname $0)
# this has been a test of the Linux filesystem; we now return you to your previous program.. :)
cd $__PWD__
【讨论】:
对于 bash 脚本解决方案
【讨论】:
只是一个想法:
#!/usr/bin/env bash
# "$0" will expand to the name of the script, as called from the command line
readlink -f $0
【讨论】:
readlink 并非完全可移植。 OSX(一般来说可能是BSD?)有一个完全不同的版本——不支持-f。相反,-f 意味着不同的东西(在这里没有帮助)。
echo $(readlink -f $0) 在 OSX 10.6 上运行良好,刚刚测试过。
echo。 readlink -f $0 本身不起作用吗?
coreutils 而不带 g 前缀。以下是我运行该命令时发生的情况:readlink: illegal option -- f(是的,我在 10.6 上。我实际上也有 gnu 的 readlink,但仅在别名 greadlink 下。例如,pastie.org/1057557。)跨度>