Check string for substring with dash

2.1k views Asked by At

I want my motd to make a nice overview of my system status. ATM I'm trying to check if a deamon is running or not and color it accordingly to it's status.

So normally you would enter deamon_name status and it outputs something like Deamon_name running / not running I got it to the point where I check if the Not is contained or not. That worked.

but then I noticed, that when I actually login and trigger the MOTD, I get some wrong information, I then noticed that I need to use dash and not bash or shell. And now my compare funtion does'nt work anymore.

if [[ $Server_name =~ .*Not.* ]]
    then 
        printf "NOT RUNNING";
    else 
        printf "RUNNING";
fi

This is my compare function and the check (later I want to add colors red/green)

$Server_name Not running. or running

2

There are 2 answers

0
globus243 On

I solved it by comparing the whole Server Running or Not Running string from the init script, since I know those messages and dash does not support extended features, this seems appropriate.

if [ "$ServerName" = "Not running." ]                # I know those messages
    then 
        printf '%b' "\033[31;1mNOT RUNNING\033[0m"   # print NOT RUNNING in red
    else 
        printf '%b' "\033[32;1mRUNNING\033[0m"       # print RUNNING in greend
fi

printf "\n"
0
Scrutinizer On

In dash you can do pattern matching with a case statement, which would also work in bash:

case $Server_name in 
  (*Not*) printf "NOT RUNNING" ;;
  (*)     printf "RUNNING"
esac

or

case $Server_name in 
  (*Not*) printf "NOT "
esac
printf "RUNNING"