systemctl을 사용하여 쉘 스크립트를 만드는 방법

systemctl을 사용하여 쉘 스크립트를 만드는 방법

스크립트를 작성하려고 했는데 작동하지 않습니다. 도움을 주실 수 있나요?

나는 서비스 이름을 쓴 다음 해당 서비스의 상태를 표시하도록 요청하는 systemctl 명령에 대한 스크립트를 작성 중입니다. 서비스가 존재하지 않으면 서비스가 존재하지 않는다는 오류 메시지가 표시되어야 합니다.

read -p "Write the name of service : " systemctl

if 
systemctl "$service"
then
echo $service
else
echo "Don't exist the service"
fi

이 오류가 발생합니다.

Write the name of service: colord.service 
Unknown operation .
Don't exist the service

이 문제를 어떻게 해결할 수 있나요?

답변1

우선, 왜 이에 대한 스크립트를 작성합니까? 이 systemctl명령은 이미 수행되었습니다.

$ systemctl status atd.service | head
● atd.service - Deferred execution scheduler
     Loaded: loaded (/usr/lib/systemd/system/atd.service; disabled; vendor preset: disabled)
     Active: active (running) since Sun 2020-10-04 14:15:04 EEST; 3h 56min ago
       Docs: man:atd(8)
    Process: 2390931 ExecStartPre=/usr/bin/find /var/spool/atd -type f -name =* -not -newercc /run/systemd -delete (code=exited, status=0/SUCCESS)
   Main PID: 2390932 (atd)
      Tasks: 1 (limit: 38354)
     Memory: 2.8M
     CGroup: /system.slice/atd.service
             └─2390932 /usr/bin/atd -f

그리고 존재하지 않는 서비스를 제공하는 경우:

$ systemctl status foo.service 
Unit foo.service could not be found.

따라서 이미 필요한 작업을 수행하고 있는 것 같습니다. 어쨌든 스크립트가 수행하려는 작업을 수행하려면 다음을 변경해야 합니다 read.

read -p "Write the name of service : " systemctl

이것은 변수에 입력한 내용을 읽습니다 $systemctl. 하지만 그 변수는 절대 사용하지 마세요. 대신 다음을 사용합니다.

systemctl "$service"

정의한 적이 없으므로 $service빈 문자열이므로 다음을 실행하면 됩니다.

$ systemctl ""
Unknown command verb .

당신이하고 싶은 일은 이것이다 :

#!/bin/sh
read -p "Write the name of service : " service

if 
  systemctl | grep -q "$service"
then
  systemctl status "$service"
else
  echo "The service doesn't exist"
fi

또는 명령줄에서 인수를 전달하는 것이 사용자가 입력하는 것보다 거의 항상 낫기 때문에(입력하면 실수하기 쉽고 전체 명령이 기록에 표시되지 않으며 자동화할 수 없습니다) , 입력하지 마세요):

#!/bin/sh

service=$1
if 
  systemctl | grep -q "$service"
then
  systemctl status "$service"
else
  echo "The service doesn't exist"
fi

그런 다음 다음을 실행하십시오.

foo.sh colord.service

관련 정보