您的位置:首页 > 运维架构 > Shell

如何获得 sh 或 source 执行的shell 脚本位置

2013-05-13 22:53 435 查看
1) 支持从其他目录执行,如 source xxx/yyy/test.sh
1) 支持 sh 和 source 执行
2) 支持路径中有空格
3) 支持 zsh 跟 bash

#!/bin/sh

if [ "$0" = "bash" ]; then
        cd "$(dirname "$BASH_SOURCE")"
        CUR_FILE=$(pwd)/$(basename "$BASH_SOURCE")
        CUR_DIR=$(dirname "$CUR_FILE")
        cd - > /dev/null
else
        echo "$0" | grep -q "$PWD"
        if [ $? -eq 0 ]; then
                CUR_FILE=$0
        else
                CUR_FILE=$(pwd)/$0
        fi
        CUR_DIR=$(dirname "$CUR_FILE")
fi

echo $CUR_DIR

为什么这么多双引号?
参考:http://tech.idv2.com/2008/01/09/bash-pitfalls/

为什么else里有个判断?
使用virtualenvwrapper时,workon xxx, 自定义 xxx/bin/postactive 中这样用时,$0不知道为什么不是相对路径,而是绝对路径

从这里:http://stackoverflow.com/questions/5708339/script-full-name-and-path-0-not-visible-when-called,得到启发,判断$0的值以分解问题;
从这里:http://bbs.chinaunix.net/thread-1288910-2-1.html,得到了正确的方法。

附:
还不能写成函数,否则zsh中source执行时函数内的$0不正确,导致结果不正确,sh执行没问题。
比如 source test\ space/get_cur_dir.sh,函数外$0为test space/get_cur_dir.sh,函数内$0为get_cur_dir
写成函数,bash没问题。

不喜欢shell 脚本,就这个在其他语言里很简单的功能,耗费了我大量时间搜索跟测试!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: