파이프라인의 행 수를 가져옵니다.

파이프라인의 행 수를 가져옵니다.

다음과 같은 bash 스크립트가 있습니다.

some_process | sort -u | other_process >> some_file

데이터를 스트리밍하는 동안 데이터가 정렬된 후 other_process에 의해 처리되기 전에 행 수를 가져오고 싶습니다. 다음과 같이 시도했습니다.

some_process | sort -u | tee >(wc -l > $some_var_i_can_print_later) | other_process >> some_file

이것은 나에게 작동하지 않습니다. 파이프에서 데이터를 전송하는 동안 변수에 카운트를 저장할 수 있는 방법이 있습니까?

또한 청소에 대해 걱정해야 하는 tmpfiles 사용을 피하고 싶습니다.

답변1

파일 설명자를 사용하면 한 단계 더 발전할 수 있습니다.

VAR=$(
  exec 3>&1
  some_process | sort -u | tee >(wc -l >&3) | other_process >> some_file
)

또는:

VAR=$({
  some_process | sort -u | tee >(wc -l >&3) | other_process >> some_file
} 3>&1)

other_processs의 출력은 에 추가되지만 some_files wc -l는 fd로 리디렉션되어 3VAR에 할당될 원래 stdout을 가리킵니다.

관련 정보