You are not logged in.

#1 2022-10-23 12:01:36

jl2
Member
From: 47° 18' N 8° 34' E
Registered: 2022-06-01
Posts: 270
Website

else not run with an if-else statement [solved]

I am writing a script to toggle a systemctl service:

#! /bin/bash

if [ "$(sudo systemctl is-active cronie.cervice)"="inactive" ];
then
    sudo systemctl start cronie.service
    echo "cronie started"
else
    sudo systemctl stop cronie.service
    echo "cronie stopped"
fi

if i run the script it only starts the service but will not stop it no matter what is-active says
I have tried a one-line version with the same problem.
thanks in advance.

Last edited by jl2 (2022-10-23 12:35:46)


Why I run Arch? To "BTW I run Arch" the guy one grade younger.
And to let my siblings and cousins laugh at Arsch Linux...

Offline

#2 2022-10-23 12:12:58

astralc
Member
Registered: 2022-09-17
Posts: 64

Re: else not run with an if-else statement [solved]

add spaces around the = in the if [ ... ]

Offline

#3 2022-10-23 12:19:34

lambdarch
Member
Registered: 2021-01-10
Posts: 75

Re: else not run with an if-else statement [solved]

It would be better to do

if ! systemctl --quiet is-active cronie.cervice

Last edited by lambdarch (2022-10-23 12:20:51)

Offline

#4 2022-10-23 12:24:45

ayekat
Member
Registered: 2011-01-17
Posts: 1,589

Re: else not run with an if-else statement [solved]

To elaborate on astralc's response a bit: You've invoked test/[…] with a single argument, which according to the manpage means it simply tests if that argument is null/empty.
That is never the case, because the string would be either "active=inactive", "failed=inactive", "inactive=inactive", or any of the other cases (all of which would make the string non-null).

If you split it up as suggested by astralc, you now invoke test/[…] with 3 arguments, and (due argument 2 being `=`) instruct it to test for equality between argument 1 and argument 3, which is probably what you want.

If you do not care to handle `failed` as a state, the following would be even more direct (no need for using test/[…] or launching a subshell):

if systemctl is-active --quiet cronie.service; then
    # stop service here
else
    # start service here
fi

--edit Ah, too slow, the second part is now a slight repetition of lambdarch's suggestion.

Last edited by ayekat (2022-10-23 12:28:52)


pkgshackscfgblag

Offline

#5 2022-10-23 12:35:29

jl2
Member
From: 47° 18' N 8° 34' E
Registered: 2022-06-01
Posts: 270
Website

Re: else not run with an if-else statement [solved]

thanks, it works now, i took lambdarchs version


Why I run Arch? To "BTW I run Arch" the guy one grade younger.
And to let my siblings and cousins laugh at Arsch Linux...

Offline

Board footer

Powered by FluxBB