如何使用 systemctl 创建 shell 脚本

Jon*_*nas 1 shell ubuntu shell-script

我一直在尝试创建一个脚本,但没有成功,如果你能帮我...

我正在 systemctl 命令上编写一个脚本,它应该要求您写下服务的名称,然后向您显示该服务的状态。如果该服务不存在,它应该向您显示一条错误消息,指出该服务不存在。

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

if 
systemctl "$service"
then
echo $service
else
echo "Don't exist the service"
fi
Run Code Online (Sandbox Code Playgroud)

我得到这个错误

Write the name of service: colord.service 
Unknown operation .
Don't exist the service
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

ter*_*don 5

首先,为什么要为此编写脚本?该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
Run Code Online (Sandbox Code Playgroud)

而且,当您为其提供不存在的服务时:

$ systemctl status foo.service 
Unit foo.service could not be found.
Run Code Online (Sandbox Code Playgroud)

所以看起来它已经可以做你需要的了。无论如何,为了执行您的脚本所尝试的操作,您需要更改您的read

read -p "Write the name of service : " systemctl
Run Code Online (Sandbox Code Playgroud)

这将读取您在变量中输入的任何内容$systemctl。但是你永远不会使用那个变量。相反,您使用:

systemctl "$service"
Run Code Online (Sandbox Code Playgroud)

由于您从未定义过$service,这是一个空字符串,所以您只是在运行:

$ systemctl ""
Unknown command verb .
Run Code Online (Sandbox Code Playgroud)

你想要做的是这样的:

$ systemctl ""
Unknown command verb .
Run Code Online (Sandbox Code Playgroud)

或者,因为在命令行上传递参数几乎总是更好,而不是让您的用户输入它们(如果您输入,很容易出错,完整的命令不会出现在历史记录中,您无法自动化它,只是不要打字):

#!/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
Run Code Online (Sandbox Code Playgroud)

然后运行:

foo.sh colord.service
Run Code Online (Sandbox Code Playgroud)