명령 출력의 첫 번째 줄을 읽습니다. 이 명령은 나를 원격 터미널에 연결합니다

명령 출력의 첫 번째 줄을 읽습니다. 이 명령은 나를 원격 터미널에 연결합니다

1 부

my_command여러 줄을 출력하는 명령이 있다고 가정해 보겠습니다.

my_command스크립트가 준비되는 즉시 my_command실행을 유지하면서 출력의 첫 번째 줄을 캡처 하고 싶습니다 .

나는 다음과 같은 것이 효과가 있을 것이라고 생각합니다.

# Get a code that `my_command` prints in its first line
parsed_first_line=`my_command | grep -oEe '[0-9]+'` 
echo 'Here is the first line ' $parsed_first_line

그러나 그것은 진실이 아니다. echo 문은 완전히 완료된 후에만 도착하는데 my_command, 이는 제가 원하는 것이 아닙니다.

2 부

더 자세히 알아보기: Imagine은 my_command실제로 내 쉘을 원격 쉘에 연결하는 명령입니다. 이로 인해 우리 솔루션이 어떤 방식으로 변경됩니까?1 부?

세부 사항이 중요한 경우 my_command실제로는 한 줄 명령입니다.

bsub /bin/zsh.

이것은Platform LSF로그인된 시스템(이 경우 대화형 zsh 셸)에서 원격 그리드로 작업을 제출하는 명령입니다. 제출된 작업이 그리드에 슬롯을 확보하면 LSF는 이를 예약하여 원격 시스템에 대화형 셸을 제공합니다.

첫 번째는 내 작업을 원격 대기열(스크립트에서 구문 분석하려는 내용)에 출력하는 것 bsub입니다 . 그런 다음 슬롯이 열리면 내 작업을 예약합니다.job ID

간단한 해결방법이 있는지 알고 싶습니다 1 부될거야2 부

답변1

일반적으로 read한 번에 한 줄씩 입력을 받습니다. 다음을 수행할 수 있습니다.

my_command | { 
  read line
  line=$(grep -oEe '[0-9]+');
  if [ $line ]; then
    echo 'Here is the first line ' $line
  fi
  #possibly read more from my_command, transfer control to another program via `exec`, etc...
 }

답변2

헤드 -1로 직접 파이프하지 않는 이유는 무엇입니까?

# Get a code that `my_command` prints in its first line
# parsed_first_line=`my_command | grep -oEe '[0-9]+'`
parsed_first_line=$( my_command | head -1 | grep -oEe '[0-9]+' )
echo 'Here is the first line ' $parsed_first_line

이렇게 하면 my_command도 완료되지만 첫 번째 줄만 반환되며, 그런 다음 grep과 일치할 수 있습니다.

답변3

이는 에 대한 것입니다 bash. zsh어쩌면 약간 다를 수도 있습니다.

#!/bin/bash

# We'll need a temporary file.
TMPFILE=`mktemp`

# Start the process in the background
my_command > $TMPFILE &

# Get its pid so we can clean up that temp file later.
PID=$!

# Wait for the first line of output
first_line=`head -n1 $TMPFILE | grep -oEe '[0-9]+'`
while [ -z "$first_line" ]; do 
    # Don't technically need this, but it'll prevent the system from grinding.
    sleep 1
    first_line=`head -n1 $TMPFILE | grep -oEe '[0-9]+'`
done

echo Result: "$first_line"

# Clean up that temp file.
wait $PID
rm $TMPFILE

관련 정보