개발관련/Linux

스크립트 자체 내에서 Bash 스크립트의 소스 디렉토리를 얻는 방법

Rateye 2021. 6. 26. 13:39
728x90
반응형
질문 : 스크립트 자체 내에서 Bash 스크립트의 소스 디렉토리를 얻으려면 어떻게해야합니까?

해당 스크립트 내부 에서 Bash 스크립트가있는 디렉토리의 경로를 어떻게 얻습니까?

Bash 스크립트를 다른 응용 프로그램의 실행기로 사용하고 싶습니다. 작업 디렉토리를 Bash 스크립트가있는 디렉토리로 변경하여 다음과 같이 해당 디렉토리의 파일에 대해 작업 할 수 있습니다.

$ ./application
답변

#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

어디에서 호출 되든 스크립트의 전체 디렉토리 이름을 제공하는 유용한 한 줄짜리입니다.

스크립트를 찾는 데 사용 된 경로의 마지막 구성 요소가 심볼릭 링크가 아닌 한 작동합니다 (디렉토리 링크는 괜찮음). 스크립트 자체에 대한 링크도 확인하려면 여러 줄 솔루션이 필요합니다.

#!/bin/bash

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 )"
      

이 마지막 것은 aliases, source , bash -c , symlinks 등의 조합과 함께 작동합니다.

주의 : 당신이 경우 cd 이 코드를 실행하기 전에 다른 디렉토리로는, 결과가 잘못 될 수 있습니다!

또한 $CDPATH gotchas 및 stderr 출력 부작용에주의하십시오 (Mac에서 update_terminal_cwd >&2 를 호출 할 때와 같은 이스케이프 시퀀스를 포함하여 대신 출력을 stderr로 리디렉션하도록 cd를 현명하게 재정의 한 경우). cd 명령 끝에 >/dev/null 2>&1 을 추가하면 두 가지 가능성이 모두 처리됩니다.

작동 방식을 이해하려면 다음과 같은 자세한 형식을 실행 해보십시오.

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
                                    

그리고 다음과 같이 인쇄됩니다.

 

SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
                                    SOURCE is './sym2/scriptdir.sh'
                                    DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
                                    DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
                                    

 

출처 : https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel
728x90
반응형