터미널에 명령 출력을 표시하지 않고 bash 스크립트에서 명령 출력에 변수를 어떻게 설정할 수 있습니까?

터미널에 명령 출력을 표시하지 않고 bash 스크립트에서 명령 출력에 변수를 어떻게 설정할 수 있습니까?

다음 스크립트를 실행해 보세요.

echo "Is autofs Enabled?"
cmd=`systemctl is-enabled autofs`
echo $cmd
if [[ $cmd = "enabled" ]]; then
echo "Yes autofs is enabled"
elif [[ $cmd = "disabled" ]]; then
echo "No autofs is disabled"
else echo "Autofs not found"
fi

autofs가 설치되지 않은 경우 스크립트 결과는 다음과 같습니다.

Failed to issue method call: No such file or directory
Autofs not found

autofs가 설치되지 않은 경우 예상되는 스크립트 출력은 다음과 같습니다.

Autofs not found

"메소드 호출을 실행할 수 없습니다: 해당 파일이나 디렉터리가 없습니다"를 인쇄하지 않도록 스크립트를 어떻게 변경합니까?

편집하다: 모두 감사합니다. 그 대답은 바로 내가 찾던 것이었다.

답변1

오류 스트림을 리디렉션하는 것은 어떻습니까 /dev/null?

[ $(systemctl is-enabled autos 2>/dev/null) = "enabled" ] && echo true || echo false

참고로 출력을 변수에 할당할 때 백틱을 사용하는 것은 쉘 이식성의 가장 낮은 공통 분모이며 최신 쉘에서는 명령에 변수를 할당하는 것으로 마이그레이션하는 것이 좋습니다.$()

답변2

생성된 메시지(stdout) systemctl와 종료 상태(후자는 $?쉘 변수를 통해)를 검사할 수 있습니다. 피하려는 오류 메시지는 stderr로 전달되므로 이를 억제하려면 해당 스트림을 리디렉션해야 합니다. 0이 아닌 종료 상태는 장치를 찾을 수 없거나 장치가 비활성화되었음을 나타낼 수 있습니다(참조:수동더 많은 정보를 알고 싶다면).

#!/bin/bash -l    
service=$1
echo "Is $service enabled?"
msg=$(systemctl is-enabled "$service" 2>/dev/null) # capture message
res=$? # capture exit code

if [ -z "$msg" ]; then  # message is empty if service not found
  echo "$service not found"
else  # service could be enabled, disabled, static, etc.
  if [ "$res" -eq 0 ]; then # enabled
    echo "Yes $service is enabled: $msg"
  else
    echo "No, $service is disabled"
  fi
fi

이 스크립트를 tmp.sh로 저장하면 다양한 입력으로 테스트할 수 있습니다.

$ ./tmp.sh autofs
    Is autofs enabled?
    Autofs not found
$ ./tmp.sh anacron.timer
    Is anacron.timer enabled?
    Yes anacron.timer is enabled: enabled
$ ./tmp.sh runlevel6.target
    Is runlevel6.target enabled?
    No, runlevel6.target is disabled

case다양한 다른 경우를 고려하면 상태를 보다 세부적으로 처리하기 위해 명령문을 사용하는 것이 더 나을 수 있습니다 .

case "$msg" in
    enabled*)  echo "Yes $service is enabled" ;;
    disabled) echo "No, $service is disabled" ;;
    linked*) # etc..
    ;;
    static*) # etc..
    ;;
esac

관련 정보