0

I'm building an array from the output of a command. Each line of output is one item in the array. I'm then iterating through each item and testing for a certain sequence of characters.

#!/bin/bash

readarray -t LST < <(#read in single or multiline output from command)
d="sometext:123"
SUBS=":$(echo $d | cut -d':' -f 2)"
for i in "${LST[@]}"
do
  if [[ $i == *"$SUBS"* ]]
  then
    #save $i in new variable
    exit 0
  fi
done
echo "no match"
exit 1

The problem appears to have something to do with the $SUBS variable. If I echo $SUBS based on the above, it outputs :123, but the comparison apparently returns false. If I populate SUBS this way:

SUBS=":123"

The comparison appears to work as expected. With any other method of populating $SUBS I've tried, the comparison seems to return false. The issue is, $d might not contain ":123" exactly. It could be ":456" or some other number preceded by a :.

closed as off-topic by Jeff Schaller, G-Man, sam, garethTheRed, Archemar Dec 30 '17 at 8:54

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Jeff Schaller, G-Man, sam, garethTheRed, Archemar
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    works here; what's the she-bang line? If it's /bin/sh, is /bin/sh dash instead of bash? (wiki.ubuntu.com/DashAsBinSh) – Jeff Schaller Dec 22 '17 at 17:45
  • it's #!/bin/bash – lightwing Dec 22 '17 at 17:49
  • It might be worth adding that my system is RHEL 6.9. – lightwing Dec 22 '17 at 17:55
  • @ilkkachu in my first attempt, I was finding the index of the : character, subtracting 1 from it to include the : and then getting the substring like this: SUBS=${d:$IndexOfColonMinusOne} This was also returning false when it would hit the comparison. – lightwing Dec 22 '17 at 18:10
  • It may be helpful to include a sample run with set -x enabled. – Jeff Schaller Dec 22 '17 at 18:23
1

Using Jeff Schaller's suggestion to use set -x (see comments above), in the output, I found a line similar to /bin/bash = /bin/ksh. This prompted me to google what I was searching for with ksh instead of bash. I came across this post:

how-do-you-tell-if-a-string-contains-another-string-in-unix-shell-scripting

According to the accepted answer, I changed my if line to:

if test "${i#*$SUBS}" == "$i"

This appears to resolve the issue I was experiencing.

Not the answer you're looking for? Browse other questions tagged or ask your own question.