Bash script absolute path with OS X

后端 未结 15 1030
误落风尘
误落风尘 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:40

    Based on the communication with commenter, I agreed that it is very hard and has no trival way to implement a realpath behaves totally same as Ubuntu.

    But the following version, can handle corner cases best answer can't and satisfy my daily needs on macbook. Put this code into your ~/.bashrc and remember:

    • arg can only be 1 file or dir, no wildcard
    • no spaces in the dir or file name
    • at least the file or dir's parent dir exists
    • feel free to use . .. / thing, these are safe

        # 1. if is a dir, try cd and pwd
        # 2. if is a file, try cd its parent and concat dir+file
        realpath() {
         [ "$1" = "" ] && return 1
    
         dir=`dirname "$1"`
         file=`basename "$1"`
    
         last=`pwd`
    
         [ -d "$dir" ] && cd $dir || return 1
         if [ -d "$file" ];
         then
           # case 1
           cd $file && pwd || return 1
         else
           # case 2
           echo `pwd`/$file | sed 's/\/\//\//g'
         fi
    
         cd $last
        }
    

提交回复
热议问题