2

I have the following in bash:

string="/opt/directory/"

Then when I do the following:

if [[ $string != *"directory"* ]]

it interprets as if the directory is not within string. Why? How can I solve this issue?

EDIT:

I feel really silly about this, I actually had made a few changes to my script, using the forward slash one of them and I could not figured out what was wrong for about an hour and after one of you mentioned it should work like this I realised it was because somewhere in the middle I had reassigned the variable to something else, that's why it wasn't picking it up.

Perhaps I will delete this question, as it really was my fault and I don't feel it will add much to anyone!

2
  • The most difficult bugs have the simplest causes, and they often cause us to go D'oh!
    – andy256
    Nov 30, 2015 at 21:57
  • Someone else will find this and go D'oh! too, so just leave it in...
    – Fabby
    Dec 14, 2015 at 23:06

2 Answers 2

2

It seems to work correctly. If I try this:

string="/opt/directory/"

if [[ $string != *"directory"* ]]; then
    echo "true"
else
    echo "false"
fi

Then it correctly reports false. In other words, the question "does $string not contain *"directory"*" is false, as $string does contain *"directory"*.


Perhaps you meant to ask "does $string contain *"directory"*", in which case you have to use:

if [[ $string == *"directory"* ]]

(Note the use of == instead of !=.)

0

Using:

string="/opt/directory/"
if [[ $string != *directory* ]]; then
    echo "not found"
else
    echo "found"
fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .