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

おすすめ記事