질문:

질문:

질문:

명령 결과를 변수에 저장하면 portcheck예상대로 작동하지 않습니다. 내 스크립트에 이 메서드가 포함되어 있습니다.

#!/bin/bash
...

status() {
    portcheck=$(nc -z -v -w5 localhost 8443)
    echo "*${portcheck}*"
    if [[ $portcheck == *refused* ]]; then
          echo "Application is stopped"
    elif [[ $portcheck == *succeeded* ]]; then
          echo "Application is started"
    else
          echo "state unknown"
    fi
}

myscript를 실행하면 다음과 같은 결과가 나타납니다.

> $  ./myscript status 
> Connection to localhost 8443 port [tcp/*] succeeded!
> ** 
> state unknown

하지만 내가 원하는 것은 명령의 결과가 변수에 저장되고 portcheck출력이 다음과 같아야 한다는 것입니다.

> $  ./myscript status 
> Connection to localhost 8443 port [tcp/*] succeeded!
> *Connection to localhost 8443 port [tcp/*] succeeded!* 
> Application is started

나는 다음을 기반으로 여러 가지 변형을 시도했습니다. https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash 기타 예:

portcheck=`nc -z -v -w5 localhost 8443`

바꾸다

portcheck=$(nc -z -v -w5 localhost 8443)

그러나 그것은 작동하지 않았습니다. 내가 뭘 잘못했나요?

배경:

주문하다

nc -z -v -w5 localhost 8443

포트가 연결 가능한지 확인하세요. 그것은 돌아온다

Connection to localhost 8443 port [tcp/*] succeeded!

포트가 "열려" 있고

nc: connect to localhost port 8443 (tcp) failed: Connection refused

포트가 "닫힌" 경우.

bash에서 간단히 명령을 실행하면 제대로 작동합니다.

답변1

호출은 nc기본적으로 stderr로 인쇄되므로 다음과 같이 출력을 stdout으로 보내야 합니다.

portcheck=$(nc -z -v -w5 localhost 8443 2>&1)
echo "*${portcheck}*"

이 경우 출력은 다음과 같습니다.

*Connection to localhost 8443 port [tcp/*] succeeded!*

관련 정보