我一直在尝试创建一个脚本,但它不起作用,如果你能帮助我......
我正在 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