寫了一個Bash script,要知道此script所在的位置,簡單方式如下:
#!/bin/sh
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
echo $DIR
上述顯示的是完整路徑。若此路徑是透過symbolic link連結過去,顯示的會是透過symbolic link的完整路徑;若想要取得的路徑是非symbolic link過去,而是絕對的路徑,那就要用下面的方式:
#!/bin/sh
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
echo $DIR
使用Bash的函式來寫上面的功能
#!/bin/sh
symlink_path () {
SD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
echo $SD
}
absolute_path() {
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]
do
AD="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
AD="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
echo $AD
}
PRG=`basename "$0"`
DIR=$(symlink_path)
echo "This script with its symlink path is:"
printf "$DIR/$PRG\n\n"
PRG=`basename "$0"`
DIR=$(absolute_path)
echo "This script with its absolute path is:"
printf "$DIR/$PRG\n\n"
參考資料
_EOF_
沒有留言:
張貼留言