programing tip

bash 쉘 스크립트에 파일을 포함하는 방법

itbloger 2020. 8. 28. 07:06
반응형

bash 쉘 스크립트에 파일을 포함하는 방법


기능에 액세스 할 수 있도록 셸 스크립트에 다른 셸 스크립트를 포함하는 방법이 있습니까?

PHP 에서처럼 include단순히 함수 이름을 호출하여 내부에 포함 된 함수를 실행하기 위해 다른 PHP 파일과 함께 지시문을 사용할 수 있습니다 .


간단히 스크립트 안에 넣으십시오.

source FILE

또는

. FILE

그건 같은거야.

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.

위의 답변은 정확하지만 다른 폴더에서 스크립트를 실행하면 문제가 발생합니다.

예를 들어, a.sh그리고 b.shA가 B와 함께 포함되어, 동일한 폴더에 . ./b.sh포함하도록한다.

예를 들어를 사용하여 폴더에서 스크립트를 실행하면 xx/xx/xx/a.sh파일 b.sh을 찾을 수 없습니다 ./b.sh: No such file or directory..

나는 사용한다

. $(dirname "$0")/b.sh

예, 소스 또는 짧은 형식을 사용 하십시오 ..

. other_script.sh

내 상황 color.sh에서 같은 디렉토리에서 를 포함하려면 init.sh다음과 같이해야합니다.

. ./color.sh

왜 그 이유는 확실 ./하지 않습니다 color.sh. 의 내용은 color.sh다음과 같습니다.

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

사용은 File color.sh오류가 아니지만 색상이 표시되지 않습니다. 나는 이것을 테스트 Ubuntu 18.04했으며 Bash버전은 다음 같습니다.

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

참고 URL : https://stackoverflow.com/questions/10823635/how-to-include-file-in-a-bash-shell-script

반응형