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

前端 未结 16 2207
我寻月下人不归
我寻月下人不归 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 04:12

    As theMarko suggests:

    BASEDIR=$(dirname $0)
    echo $BASEDIR
    

    This works unless you execute the script from the same directory where the script resides, in which case you get a value of '.'

    To get around that issue use:

    current_dir=$(pwd)
    script_dir=$(dirname $0)
    
    if [ $script_dir = '.' ]
    then
    script_dir="$current_dir"
    fi
    

    You can now use the variable current_dir throughout your script to refer to the script directory. However this may still have the symlink issue.

提交回复
热议问题