OR grep을 수행하는 방법(다른 GREP_COLOR 설정 사용)

OR grep을 수행하는 방법(다른 GREP_COLOR 설정 사용)

따라서 동적 motd의 서비스 상태를 강조하고 싶습니다. 현재 php-fpm에서 다음 명령을 사용하고 있습니다.

service php5-fpm status|grep Active|cut -d':' -f2-

이를 달성하기 위해 여러 가지 솔루션을 시도했습니다. 다음 두 가지는 1/ 모든 것이 정상일 때 2/ 다른 모든 상황을 감지하는 훌륭한 작업을 수행합니다.

service php5-fpm status|grep Active|cut -d':' -f2-|GREP_COLOR='1;32' grep --color=always " active \(.*\)"

service php5-fpm status|grep Active|cut -d':' -f2-|GREP_COLOR='1;31' grep --color=always -E ".* \(.*\)"

내가 하려는 것은 ||. 첫 번째 grep이 0을 반환하면 제대로 작동하지만 실패하고 1을 반환하면 두 번째 grep이 작동하지 않는 것 같습니다.

service php5-fpm status|grep Active|cut -d':' -f2-|(GREP_COLOR='1;32' grep --color=always -E " active \(.*\)" || GREP_COLOR='1;31' grep --color=always -E ".* \(.*\)")

bash -x로 실행하면 다음과 같은 출력이 표시됩니다.

+ GREP_COLOR='1;32'
+ grep --color=always -E ' active \(.*\)'
+ cut -d: -f2-
+ grep Active
+ service php5-fpm status
+ GREP_COLOR='1;31'
+ grep --color=always -E '.* \(.*\)'

그래서... 지금은 잘 모르겠고 누군가 내가 뭘 잘못하고 있는지 알아주길 바랍니다.

답변1

Where will the 2nd grep get it's input from when the 1st grep fails?
Coz, grep1 consumes all the stdin with nothing left for grep2.In the
case of grep1 succeeding, grep2 never runs so is not an issue.

We may rig it up like the following to achieve what you want:

#/bin/sh
service php5-fpm status |
grep Active |
cut -d':' -f2- | tee /tmp/log |
GREP_COLOR='1;32' grep --color=always -E " active \(.*\)" - ||
GREP_COLOR='1;31' grep --color=always -E ".* \(.*\)") /tmp/log

답변2

좋아요, 임시 파일을 만들고 싶지 않기 때문에 내 질문에 대한 Rakesh Sharma의 의견을 바탕으로 한 나만의 솔루션은 다음과 같습니다.

function service_status() {
    status=`service $1 status | grep Active | cut -d':' -f2-`
    echo "$status" | GREP_COLOR='1;32' grep --color=always -E "^ active \(.*\)" || \
    echo "$status" | GREP_COLOR='1;31' grep --color=always -E ".* \(.*\)"
}

관련 정보