You are not logged in.

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

jl2
Member
Registered: 2022-06-01
Posts: 26

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)


"Growing old isn't that bad if you consider the alternatives" --Maurice Chavalier

Offline

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

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

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: 50

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,552
Website

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)


{,META,RE}PKGBUILDSpacman-hacks (includes makemetapkg and remakepkg) │ dotfileslocaldir

Offline

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

jl2
Member
Registered: 2022-06-01
Posts: 26

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

thanks, it works now, i took lambdarchs version


"Growing old isn't that bad if you consider the alternatives" --Maurice Chavalier

Offline

Board footer

Powered by FluxBB