Home > Enterprise >  Bash check multiple word to match one word
Bash check multiple word to match one word

Time:09-22

i have a variable BACKUP_STATUS which consists of many SUCCESS words

[ryt: i9]: echo $BACKUP_STATUS
SUCCESS SUCCESS SUCCESS SUCCESS SUCCESS

Question: I want to make a check so that if one of these words in a variable changes to something else, then it gives an error I try like this

[[$BACKUP_STATUS = "SUCCESS"]] && echo true || echo false

but throws false

CodePudding user response:

You can use regex with test command to search if "NO_SUCCESS" string is found

$ SUC="SUCCESS SUCCESS SUCCESS SUCCESS SUCCESS"
$ NSUC="SUCCESS SUCCESS SUCCESS SUCCESS NO_SUCCESS"
$ [[ $SUC =~ .*NO_SUCCESS.* ]] && echo "something wrong" || echo "everything is ok"
everything is ok
$ [[ $NSUC =~ .*NO_SUCCESS.* ]] && echo "something wrong" || echo "everything is ok"
something wrong

CodePudding user response:

Try this:

[[ $(tr ' ' '\n' <<<"$BACKUP_STATUS" | sort -u) == SUCCESS ]] && echo true || echo false

CodePudding user response:

How about

if [[ " $BACKUP_STATUS" == *[^\ ]SUCCESS* || "$BACKUP_STATUS " == *SUCCESS[^\ ]* ]]
then
  echo unexpected status found
else
  echo only successes
fi 

The idea is to search for a word which has something in front or in the back of SUCCESS. It's a bit clumsy, but I could not find a way to combine the two conditions into one.

Another possibility would be to use a loop:

error=0
for statusword in $BACKUP_STATUS
do
  if [[ $statusword != SUCCESS ]]
  then
    echo Unexpected status: $statusword
    error=1
    break
  fi
done
if (( error == 0 ))
then
  # all SUCCESS
  ...
fi
      

Both solutions work without creating a child process.

CodePudding user response:

I like extended globbing and parameter parsing for this.

$:  echo "[$BACKUP_STATUS]" # value with a fail
[ SUCCESS SUCCESS SUCCESS SUCCESS SUCCESS NO_SUCCESS ]
$: shopt -s extglob         # set extended globbing

$: echo "[${BACKUP_STATUS//*( )SUCCESS*( )/}]"
[NO_]
$: [[ -z "${BACKUP_STATUS//*( )SUCCESS*( )/}" ]] && echo ok || echo no
no

$: BACKUP_STATUS=" SUCCESS SUCCESS SUCCESS SUCCESS SUCCESS " # no fails
$: echo "[${BACKUP_STATUS//*( )SUCCESS*( )/}]"
[]
$: [[ -z "${BACKUP_STATUS//*( )SUCCESS*( )/}" ]] && echo ok || echo no
ok

Extended globbing lets you have zero-or-more spaces.
${BACKUP_STATUS//*( )SUCCESS*( )/} says return the value of $BACKUP_STATUS with every occurrence of SUCCESS with or without spaces before or behind removed.

If anything is left it was not a SUCCESS return, so [[ -z ... ]] checks for a zero-length return as all successes.

This doesn't require spawning any external procs. It's just Bash.

  • Related