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

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

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



답변

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

source FILE

또는

. FILE # POSIX compliant

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


답변

구문은 source <file-name>

전의. source config.sh

스크립트-config.sh

USERNAME="satish"
EMAIL="satish@linuxconcept.com"

호출 스크립트-

#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.

여기에서 다른 bash 스크립트에 bash 스크립트포함하는 방법을 배울 수 있습니다 .


답변