You can examine the message (stdout) produced by systemctl
as well as its exit status (the latter via the $?
shell variable). The error message you seek to avoid is delivered to stderr, so you need to redirect that stream if you want to suppress it. Non-zero exit status can indicate either that the device was not found or that it was disabled (see the manual for more information).
#!/bin/bash -l service=$1 echo "Is $service enabled?" msg=$(systemctl is-enabled "$service" 2>/dev/null) # capture message res=$? # capture exit code if [ -z "$msg" ]; then # message is empty if service not found echo "$service not found" else # service could be enabled, disabled, static, etc. if [ "$res" -eq 0 ]; then # enabled echo "Yes $service is enabled: $msg" else echo "No, $service is disabled" fi fi
Saving that script as tmp.sh, you can test with various inputs:
$ ./tmp.sh autofs Is autofs enabled? Autofs not found $ ./tmp.sh anacron.timer Is anacron.timer enabled? Yes anacron.timer is enabled: enabled $ ./tmp.sh runlevel6.target Is runlevel6.target enabled? No, runlevel6.target is disabled
Given the variety of other cases, you might be better off using a case
statement for more granular handling of the status, e.g.,
case "$msg" in enabled*) echo "Yes $service is enabled" ;; disabled) echo "No, $service is disabled" ;; linked*) # etc.. ;; static*) # etc.. ;; esac