본문 바로가기

스크립트

Shell Script에서 EOF(End Of File) 사용하는 방법

반응형

Shell Script에서 EOF(End Of File) 사용하는 방법

리눅스 쉘 스크립트에서 EOF (End Of File) 또는 "Here Document"를 사용하면 스크립트 내에서 멀티라인 텍스트 블록을 정의할 수 있습니다. 이것은 주로 스크립트에서 파일이나 명령에 데이터를 전달할 때 유용합니다.

Here Document란?

Here Document는 특정 명령어에 다중 라인 입력을 제공하는 방법입니다. << 연산자와 함께 EOF와 같은 구분자를 사용해 입력의 시작과 끝을 정의합니다.

 

기본 문법

command << EOF
  line1
  line2
  ...
EOF
  • command : 입력을 받을 명령어 (예: cat, bash, ftp 등)
  • << : Here Document를 시작하는 연산자
  • EOF : 입력의 끝을 나타내는 구분자 (임의의 문자열 가능, EOF는 관례적으로 사용)

EOF 사용 예제

파일 생성

cat 명령어와 함께 EOF를 사용해 파일을 생성할 수 있습니다.

cat << EOF > output.txt
Hello, World!
This is a test file.
Created using EOF.
EOF

변수 사용

Here Document 내에서 변수와 명령어를 확장할 수 있습니다.

name="Grok"
cat << EOF
Hello, $name!
Current date: $(date)
EOF

덮어쓰기(파일이 없으면 생성됨)

file1.txt

cat <<EOF > file1.txt
hello
world
EOF
$ cat file1.txt
hello
world

file2.txt

cat <<'EOF' | sed 's/l/e/g' > file2.txt
Hello
World
EOF
$ cat file2.txt 
Heeeo
Wored

file3.txt

cat > file3.txt <<EOF
hello
world
EOF
$ cat file3.txt        
hello
world
728x90

추가(파일 끝에 붙이기)

file5.txt

cat <<EOF >> file5.txt      
hello
world
EOF
cat <<EOF >> file5.txt
hello
world
EOF
$ cat file5.txt         
hello
world
hello
world

file6.txt

cat >> file6.txt << EOF
hello
world
EOF
cat >> file6.txt << EOF
hello
world
EOF
$ cat file6.txt
hello
world
hello
world

 

728x90
반응형