[입출력 리다이렉션과 파이프]표준 입출력 리다이렉션의 개념과 사용법

표준 입출력 리다이렉션의 개념

Bash 쉘에서는 표준 입력(stdin), 표준 출력(stdout), 표준 에러(stderr)를 다른 소스나 대상으로 리다이렉션할 수 있습니다. 이를 통해 파일로의 입출력, 다른 프로세스와의 파이프 연결 등 다양한 작업을 수행할 수 있습니다.

표준 입출력 리다이렉션의 사용법

  • 표준 입력 리다이렉션(<): 파일로부터 입력을 받아옵니다.

    command < input.txt
    
  • 표준 출력 리다이렉션(>): 출력을 파일로 리다이렉션합니다. 파일이 이미 존재하는 경우 덮어쓰기를 하게 됩니다.

    command > output.txt
    
  • 표준 출력 리다이렉션(append)(>>): 출력을 파일로 리다이렉션합니다. 파일이 이미 존재하는 경우 내용을 추가합니다.

    command >> output.txt
    
  • 표준 에러 리다이렉션(2>): 에러 메시지를 파일로 리다이렉션합니다.

    command 2> error.txt
    
  • 표준 출력과 표준 에러를 같은 파일로 리다이렉션(&> 또는 >&): 표준 출력과 표준 에러를 모두 같은 파일로 리다이렉션합니다.

    command &> output_error.txt
    

쉘 스크립트 샘플 코드

#!/bin/bash

# 표준 입력 리다이렉션
echo "Enter your name:"
read name < input.txt
echo "Hello, $name!"

# 표준 출력 리다이렉션
echo "This is a sample text." > output.txt

# 표준 출력 리다이렉션 (append)
echo "This is another text." >> output.txt

# 표준 에러 리다이렉션
command_not_found 2> error.txt

# 표준 출력과 표준 에러를 같은 파일로 리다이렉션
echo "This is both output and error." &> output_error.txt

다른 함수와 함께 사용하는 코드

#!/bin/bash

# 함수 정의
process_data() {
    local data_file=$1
    local output_file=$2

    # 파일로부터 데이터 읽어오기
    while IFS= read -r line; do
        # 데이터 처리 로직
        processed_line=$(process_line "$line")

        # 표준 출력 리다이렉션
        echo "$processed_line" >> "$output_file"
    done < "$data_file"
}

# 다른 함수와 함께 사용
process_line() {
    local line=$1

    # 데이터 처리 로직
   

 processed_data=$(some_processing "$line")

    echo "$processed_data"
}

# main 함수
main() {
    local input_file="data.txt"
    local output_file="processed.txt"

    # 데이터 처리 함수 호출
    process_data "$input_file" "$output_file"
}

# main 함수 실행
main

조건문과 반복문과 함께 사용하는 샘플 코드

#!/bin/bash

# 조건문과 함께 사용
if [[ -f "input.txt" ]]; then
    cat "input.txt" > "output.txt"
fi

# 반복문과 함께 사용
for file in *.txt; do
    echo "Processing $file..."
    process_file "$file"
done

성능 향상을 위한 팁

  • 필요한 경우에만 입출력 리다이렉션을 사용하세요. 불필요한 리다이렉션은 성능 저하를 가져올 수 있습니다.
  • 대용량 파일의 경우, 리다이렉션 대신 파이프(|)를 사용하여 데이터를 처리하세요. 이렇게 함으로써 중간 파일을 생성하지 않아 성능을 향상시킬 수 있습니다.