Bash script absolute path with OS X

后端 未结 15 1022
误落风尘
误落风尘 2020-11-29 18:20

I am trying to obtain the absolute path to the currently running script on OS X.

I saw many replies going for readlink -f $0. However since OS X\'s

15条回答
  •  孤城傲影
    2020-11-29 18:54

    There's a realpath() C function that'll do the job, but I'm not seeing anything available on the command-line. Here's a quick and dirty replacement:

    #!/bin/bash
    
    realpath() {
        [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
    }
    
    realpath "$0"
    

    This prints the path verbatim if it begins with a /. If not it must be a relative path, so it prepends $PWD to the front. The #./ part strips off ./ from the front of $1.

提交回复
热议问题