[Shell Tips] 找出正在執行中的shell script 的絕對路徑

通常我們可以用 dirname $0 來取出此shell script 的路徑名稱. 但是這個路徑有可能是相對路徑. 但是有時候我想知道絕對路徑時, 該如何用呢?

如下範例:

假設 /dirA/dirB/the_schell.sh 內容如下

#!/bin/bash
DIR_PATH=$(dirname $0)
FULL_DIR_PATH=$(cd $(dirname $0) && pwd)
echo DIR_PATH=$DIR_PATH
echo FULL_DIR_PATH=$FULL_DIR_PATH

若我在/dirA 目錄下執行此程式

# cd /dirA
# ./dirB/the_shell.sh
DIR_PATH=./dirB
FULL_DIR_PATH=/dirA/dirB
This entry was posted in shell script and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *