1

Pulling disk status from a disk array, I get "ready" and "online" as status for OK. Trying to trap this with an IF statement in bash, that will act if the value is something else than "ready" and "online".

The code snippet below works for trapping "OK" but I'd like to reverse it, so it traps if $diskstatus is NOT ready or online.

#!/bin/bash
diskstatus="online"
if [[ $diskstatus = online ]] || [[ $diskstatus = ready ]]; then echo "OK: $diskstatus"; fi

Have now tried nearly everything with brackets, quotes and whatnot but not getting any of it to work.

4 Answers 4

3

Just for completeness, consider also the case statement.

case $diskstatus in
    online | ready) ;;
    *) echo "Not ok: $diskstatus";;
esac

The syntax may look arcane at first but you quickly get used to it. I actually tend to prefer it over if for many things involving simple string pattern matching. As a bonus, it's compatible with traditional sh.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, didn't think about that. I use case a lot in command input parameter parsing.
2

Use the regex operator in bash with [[ operator as below,

[[ ! $diskstatus =~ ^(ready|online)$ ]] && echo "Not OK: $diskstatus"

Also, observe that double-quotes are not needed either for the regex or for the variable part, because neither word-splitting nor pathname expansion(globbing) will be performed in this context

Another POSIX way to do this, to add to tripleee's answer would be as

if [ "$diskstatus" != "ready" ] && [ "$diskstatus" != "online" ]; then  echo "Not OK: $diskstatus"; fi

2 Comments

I had this solution in my mind, but I was squeezing my head how to make it work. Nice job.
Thanks for the regex variety, for the sake of readability it is very elegant. I'll pick this one :)
0

Since both need to be false, you have to use an and statement.

if [[ $diskstatus != online ]] && [[ $diskstatus != ready ]]; then echo "OK: $diskstatus"; fi

Otherwise, since at least one of the conditions will always be true, your if statement's body will always run.

Comments

0

simply reversing equality and logical operator seems to work for me

$ diskstatus=onlin
$ if [[ $diskstatus != online ]] && [[ $diskstatus != ready ]]; then echo "NOK: $diskstatus"; fi
NOK: onlin

2 Comments

There is no reason to export the variable here.
@tripleee you're right, I removed the useless but harmless export

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.