Shell-Script
如何使用 systemctl 創建 shell 腳本
我一直在嘗試創建一個腳本,但它沒有成功,如果你能幫助我……
我在 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
我該如何解決這個問題?
首先,您為什麼要為此編寫腳本?該
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