이 코드는 Makefile에서 디렉토리 내 파일이 존재하는지 확인하기 위해 사용되는 구문입니다. 이를 세부적으로 나누어 설명하겠습니다.
1. 구문 전체
-@[ -n "$(wildcard reports/*)" ]
구성 요소:
-@:-: 명령어 실행 중 오류가 발생해도 Makefile 실행을 중단하지 않도록 설정.@: 해당 명령어를 터미널에 출력하지 않음.
[ -n "$(wildcard reports/*)" ]:[와]: 조건식을 작성하는 데 사용되는 POSIX 표준 구문.-n: 문자열이 비어 있지 않음을 확인하는 테스트 옵션.$(wildcard reports/*):reports/디렉토리에서 파일 목록을 가져오는 Makefile 함수.
2. $(wildcard reports/*)
설명:
- Makefile의
wildcard함수는 주어진 경로 패턴(여기서는reports/*)에 해당하는 모든 파일 경로를 문자열로 반환합니다. - 예:
reports/디렉토리에file1.txt,file2.log가 있다면:
반환값:$(wildcard reports/*)reports/file1.txt reports/file2.logreports/디렉토리가 비어 있다면:
반환값: 빈 문자열$(wildcard reports/*)"".
3. [ -n "<string>" ]
설명:
-n은 문자열이 비어 있지 않은지 확인하는 조건식입니다.예:
[ -n "reports/file1.txt" ]- 문자열이 비어 있지 않으므로 조건은 참(True)입니다.
[ -n "" ]- 문자열이 비어 있으므로 조건은 거짓(False)입니다.
4. 종합 동작
- 구문:
-@[ -n "$(wildcard reports/*)" ] && gzip -f reports/* || echo "No files to compress in reports/"
동작 흐름:
$(wildcard reports/*)로reports/디렉토리 내 파일 목록을 가져옵니다.- 파일이 있으면
reports/file1.txt reports/file2.log와 같은 문자열 반환. - 파일이 없으면 빈 문자열 반환.
- 파일이 있으면
[ -n "$(wildcard reports/*)" ]:- 파일이 있는 경우 참(True).
- 파일이 없는 경우 거짓(False).
&&와||:- 조건이 참(True)이면
gzip -f reports/*실행. - 조건이 거짓(False)이면
echo "No files to compress in reports/"실행.
- 조건이 참(True)이면
5. 예제
디렉토리 구조
reports/
file1.txt
logs/
(empty)
Makefile 코드
gzip_step:
@echo "Running gzip_step..."
-@[ -n "$(wildcard reports/*)" ] && gzip -f reports/* || echo "No files to compress in reports/"
-@[ -n "$(wildcard logs/*)" ] && gzip -f logs/* || echo "No files to compress in logs/"
실행
make gzip_step
출력
Running gzip_step...
gzip: reports/file1.txt
No files to compress in logs/
reports/디렉토리에 파일이 있으므로gzip명령 실행.logs/디렉토리가 비어 있으므로 "No files to compress in logs/" 메시지를 출력.
6. 코드의 의미
이 코드는 다음과 같은 목적을 달성합니다:
- 디렉토리 검사:
$(wildcard reports/*)로 파일 존재 여부를 확인. - 불필요한 오류 방지: 빈 디렉토리에서
gzip명령을 실행하면 오류가 발생할 수 있으므로 이를 방지. - 유연성 제공: 파일이 없을 경우 사용자에게 명확한 메시지를 출력.
7. 추가 참고
$(wildcard ...)의 응용:
특정 확장자를 가진 파일만 처리:
$(wildcard reports/*.log)reports/디렉토리 내.log파일만 반환.
파일 경로를 처리하는 다른 Makefile 함수와 조합:
$(notdir $(wildcard reports/*))- 반환값: 파일 이름만 반환 (디렉토리 경로 제거).
이 코드는 디렉토리 내 파일 유무에 따라 동작을 분기하는 방법을 효과적으로 보여줍니다. Makefile에서 파일 기반 작업을 효율적으로 관리하고, 불필요한 오류를 방지하고 싶다면 꼭 활용해 보세요!
'IT > Software' 카테고리의 다른 글
| 리그레션 테스트 - Regression test 의미 (0) | 2024.11.26 |
|---|---|
| Makefile - 쉘 조건문 내에서 make 다른 타겟 호출 방법 (0) | 2024.11.22 |
| Makefile - `gzip`을 유연하게 다루는 방법: `@`와 `-` 옵션의 역할 (0) | 2024.11.22 |
| Makefile - 예약 및 특수 변수 정리: 효율적인 Makefile 작성 가이드 (0) | 2024.11.22 |
| Makefile - target: $(if $(findstring gzip,$(MAKECMDGOALS)),gzip_step) (0) | 2024.11.22 |