2019年1月11日 星期五

Bash顯示script所在目錄的路徑

寫了一個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 # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
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
}
#echo "$(symlink_path)"

absolute_path() {
SOURCE="${BASH_SOURCE[0]}"
  while [ -h "$SOURCE" ] 
  do # resolve $SOURCE until the file is no longer a symlink
    AD="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative sym
  done 
  AD="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  echo $AD
} 
#echo "$(absolute_path)"

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_

沒有留言:

張貼留言