【问题标题】:sh equivalent of __FILE__sh 相当于 __FILE__
【发布时间】:2010-07-23 14:18:41
【问题描述】:

是否有一个等同于__FILE__ 的sh 来给我当前执行文件的路径名? POSIX 解决方案首选,bash 可接受,谢谢。

【问题讨论】:

标签: php file shell


【解决方案1】:

尝试使用$0

【讨论】:

  • 如果您在来自另一个文件的文件中执行此操作,则这不等同于 __FILE__
【解决方案2】:

这将同时获取文件和目录

# !/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__

【讨论】:

    【解决方案3】:

    【讨论】:

      【解决方案4】:

      只是一个想法:

      #!/usr/bin/env bash
      
      # "$0" will expand to the name of the script, as called from the command line
      readlink -f $0
      

      【讨论】:

      • 如果脚本是通过 $PATH 变量调用的,那将是不正确的。
      • 请注意,readlink 并非完全可移植。 OSX(一般来说可能是BSD?)有一个完全不同的版本——不支持-f。相反,-f 意味着不同的东西(在这里没有帮助)。
      • echo $(readlink -f $0) 在 OSX 10.6 上运行良好,刚刚测试过。
      • 你为什么使用echoreadlink -f $0 本身不起作用吗?
      • @The MYYN 你必须安装 gnu 的 coreutils 而不带 g 前缀。以下是我运行该命令时发生的情况:readlink: illegal option -- f(是的,我在 10.6 上。我实际上也有 gnu 的 readlink,但仅在别名 greadlink 下。例如,pastie.org/1057557。)跨度>
      猜你喜欢
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      • 2012-09-27
      • 1970-01-01
      相关资源
      最近更新 更多