Unix shell script find out which directory the script file resides?

前端 未结 16 2009
我寻月下人不归
我寻月下人不归 2020-12-02 03:14

Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script fil

相关标签:
16条回答
  • 2020-12-02 03:48

    In Bash, you should get what you need like this:

    #!/usr/bin/env bash
    
    BASEDIR=$(dirname "$0")
    echo "$BASEDIR"
    
    0 讨论(0)
  • 2020-12-02 03:48

    An earlier comment on an answer said it, but it is easy to miss among all the other answers.

    When using bash:

    echo this file: "$BASH_SOURCE"
    echo this dir: "$(dirname "$BASH_SOURCE")"
    

    Bash Reference Manual, 5.2 Bash Variables

    0 讨论(0)
  • 2020-12-02 03:50

    This one-liner tells where the shell script is, does not matter if you ran it or if you sourced it. Also, it resolves any symbolic links involved, if that is the case:

    dir=$(dirname $(test -L "$BASH_SOURCE" && readlink -f "$BASH_SOURCE" || echo "$BASH_SOURCE"))
    

    By the way, I suppose you are using /bin/bash.

    0 讨论(0)
  • 2020-12-02 03:51

    If you're using bash....

    #!/bin/bash
    
    pushd $(dirname "${0}") > /dev/null
    basedir=$(pwd -L)
    # Use "pwd -P" for the path without links. man bash for more info.
    popd > /dev/null
    
    echo "${basedir}"
    
    0 讨论(0)
  • 2020-12-02 03:52

    Inspired by blueyed’s answer

    read < <(readlink -f $0 | xargs dirname)
    cd $REPLY
    
    0 讨论(0)
  • 2020-12-02 03:57
    cd $(dirname $(readlink -f $0))
    
    0 讨论(0)
提交回复
热议问题