Microsoft MVP성태의 닷넷 이야기
오류 유형: 773. shell script 실행 시 "$'\r': command not found" 오류 [링크 복사], [링크+제목 복사]
조회: 6552
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

shell script 실행 시 "$'\r': command not found" 오류

예를 들어 볼까요? ^^ 윈도우 환경에서 다음과 같이 간단한 shell script를 만들고,

echo "TEST"

이를 WSL 환경, 또는 리눅스 환경에서 실행하면 다음과 같이 오류가 발생합니다.

$ ./test.sh
./test.sh: line 1: $'\r': command not found
TEST
./test.sh: line 3: $'\r': command not found
./test.sh: line 5: syntax error near unexpected token `$'{\r''
'/test.sh: line 5: `{

왜냐하면, 리눅스의 경우 개행 처리가 0x0a('\n') 단일 문자이지만, 윈도우의 경우는 0x0d('\r'), 0x0a('\n') 2개의 문자이기 때문입니다. 게다가 리눅스의 bash 쉘은 '\r' 문자를 파싱해야 할 대상으로 취급하니 문제가 됩니다.




재미있는 것은, 저 규칙이 git으로 관리하는 프로젝트의 경우 혼란스러운 상황을 연출할 수 있습니다.

가령, 윈도우에서 개발하느라 리눅스에서의 사용을 고려해 ".sh" 파일만 특별하게 '\n' 단일 개행을 해서 저장했는데, 이 파일을 다른 윈도우 환경에서 git fetch로 업데이트를 받는 경우 '\r', '\n'으로 자동 변경이 됩니다.

이 규칙은 git의 core.eol / core.autocrlf로 인한 것인데요,

git 에서 CRLF 개행 문자 차이로 인한 문제 해결하기
; https://www.lesstif.com/gitbook/git-crlf-20776404.html

따라서, git fetch로 인한 업데이트 시에 ".sh" 파일의 개행을 윈도우 환경에서도 그대로 받으려면 "core.autocrlf"를 false로 설정해야 합니다.

그런데, 위의 글에 보면 false가 기본 설정이라고 하는데 비주얼 스튜디오와 함께 설치되는 git 클라이언트의 경우에는 기본값이 true로 설정돼 있습니다.

C:\temp> where git
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd\git.exe

C:\temp> git config --list
error: cannot spawn less: No such file or directory
core.symlinks=false
core.autocrlf=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
pack.packsizelimit=2g
help.format=html
http.sslcainfo=/ssl/certs/ca-bundle.crt
diff.astextplain.textconv=astextplain
rebase.autosquash=true
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
include.path=C:/Program Files (x86)/Git/etc/gitconfig
include.path=C:/Program Files/Git/etc/gitconfig
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
remote.origin.url=ssh://git@git.testgit.com:5000/testusr/test-prj.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.main.remote=origin
branch.main.merge=refs/heads/main

따라서 이런 경우에는 명시적으로 false로 설정해야 합니다.

C:\temp> git config --global core.autocrlf false

이렇게 환경 설정이 되면, 윈도우에서 get fetch해도 해당 .sh 파일을 wsl(또는 리눅스) 환경에서 정상적으로 실행할 수 있습니다.

하지만 개인적으로 저 설정을 다른 개발자 PC에서 일일이 하는 것은 다소 불편한 해결책으로 보입니다. 그보다는, sh 파일에 대한 개행을 특별히 LF만으로 처리할 것이기 때문에 ".gitattributes" 파일을 통해 개행 자동 관리에서 제외하는 설정이 더 나은 듯합니다.

# .gitattributes

*.sh     -text

(참고로 이렇게 설정 후, 타 PC의 'git fetch'에 반영하려면 대상 파일이 당연히 변경되어야 합니다. 그렇지 않으면 "git fetch"로는 변경 사항이 없으므로 다시 내려받지 않아 기존 파일이 유지될 뿐입니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/13/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13381정성태6/25/20233857오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233296스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233306스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233198오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237070오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233420.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20233100스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233207오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234520오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233205개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233236개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233407개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233225개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233361개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233496오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233276.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233016오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233808.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233370스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233310.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233741오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233125오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233458오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233784.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233569.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233886DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...