• 请不要在回答技术问题时复制粘贴 AI 生成的内容
otmb
V2EX  ›  程序员

linux shell 文件如何知道自身位置?

  •  
  •   otmb · Jan 13, 2015 · 4191 views
    This topic created in 4312 days ago, the information mentioned may be changed or developed.

    a.sh

    path=xxx

    经常使用source xxpath/a.sh 调用a.sh
    在a.sh中如何获取自身所在文件夹路径呢?

    20 replies  •  2015-01-13 17:22:58 +08:00
    eamars
    eamars
    Jan 13, 2015
    1
    cd "$(dirname "$0")"
    gamecreating
    gamecreating
    Jan 13, 2015
    2
    pwd
    otmb
    otmb
    OP
    Jan 13, 2015
    3
    @eamars 通过source a.sh,这种方法不能获取文件所在的路径
    bellchu
    bellchu
    Jan 13, 2015
    5
    realpath
    otmb
    otmb
    OP
    Jan 13, 2015
    6
    @bellchu 不行
    bellchu
    bellchu
    Jan 13, 2015
    7
    @otmb readlink呢? 有的系统可能没有realpath命令
    otmb
    otmb
    OP
    Jan 13, 2015
    8
    @bellchu 通过source调用脚本,不行的
    bellchu
    bellchu
    Jan 13, 2015
    9
    @otmb

    SCRIPTPATH=`realpath`
    otmb
    otmb
    OP
    Jan 13, 2015
    10
    @eamars bash中好像$0无论何种情况都等于$_的?
    otmb
    otmb
    OP
    Jan 13, 2015
    11
    @bellchu
    source xxx/a.sh
    你所得到的path是当前目录,而不是a.sh所在路径
    Beebird
    Beebird
    Jan 13, 2015
    12
    #!/bin/env bash
    ...
    LOCATION=$(pwd)
    #echo $LOCATION
    ...
    otmb
    otmb
    OP
    Jan 13, 2015
    13
    @Beebird source 不行的
    lululau
    lululau
    Jan 13, 2015
    14
    zsh 测试通过:

    ➜ cat test.sh
    dir=`(cd "$(dirname "$0")"; pwd)`

    ➜ 2.2.0 ~/tmp
    ➜ source test.sh

    ➜ 2.2.0 ~/tmp
    ➜ echo $dir
    /Users/liuxiang/tmp
    otmb
    otmb
    OP
    Jan 13, 2015
    15
    @lululau 为啥不用bash?
    lululau
    lululau
    Jan 13, 2015
    16
    @otmb zsh 功能比 bash 丰富很多
    lululau
    lululau
    Jan 13, 2015
    17
    @otmb bash 测试也没问题啊
    Beebird
    Beebird
    Jan 13, 2015
    18
    @otmb 试了可以啊,不论是source还是直接运行。

    cat testpwd.sh

    #!/bin/env bash

    LOCATION=$(pwd)
    echo $LOCATION


    $ source testpwd.sh
    /home/lzhao/tmp
    HowardMei
    HowardMei
    Jan 13, 2015
    19
    sh和bash下面source和直接执行需要的判断参数不同,从"$_" "$0" "$BASH_SOURCE"三个里面找,如果是curl或cat script.sh | bash方式,
    这三个都没用,参考:
    https://github.com/HowardMei/shbin/blob/master/shbin/shsrc
    KentY
    KentY
    Jan 13, 2015
    20
    我是这么弄的,也判断link的情况,readlink读真实dir

    https://github.com/sk1418/passwdmanager/blob/master/start.sh
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1329 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 21:49 · PVG 05:49 · LAX 13:49 · JFK 16:49
    ♥ Do have faith in what you're doing.