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

前端 未结 16 2206
我寻月下人不归
我寻月下人不归 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 04:11

    The original post contains the solution (ignore the responses, they don't add anything useful). The interesting work is done by the mentioned unix command readlink with option -f. Works when the script is called by an absolute as well as by a relative path.

    For bash, sh, ksh:

    #!/bin/bash 
    # Absolute path to this script, e.g. /home/user/bin/foo.sh
    SCRIPT=$(readlink -f "$0")
    # Absolute path this script is in, thus /home/user/bin
    SCRIPTPATH=$(dirname "$SCRIPT")
    echo $SCRIPTPATH
    

    For tcsh, csh:

    #!/bin/tcsh
    # Absolute path to this script, e.g. /home/user/bin/foo.csh
    set SCRIPT=`readlink -f "$0"`
    # Absolute path this script is in, thus /home/user/bin
    set SCRIPTPATH=`dirname "$SCRIPT"`
    echo $SCRIPTPATH
    

    See also: https://stackoverflow.com/a/246128/59087

提交回复
热议问题