programing

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

subpage 2023. 5. 4. 19:57
반응형

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.sh같은 폴더에 있음, 용도. ./b.shb를 포함합니다.

예를 들어 폴더에서 스크립트를 실행하는 경우xx/xx/xx/a.sh,파일b.sh찾을 수 없음:./b.sh: No such file or directory.

그래서 사용합니다.

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

예, source 또는 다음과 같은 짧은 형식을 사용합니다..:

. other_script.sh

구문은source <file-name>

전에source config.sh

스크립트 - 구성.

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

호출 스크립트 -

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

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

내 상황에서, 다음을 포함하기 위해.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

반응형