1

I write the following shell script.

#! /bin/sh

foo=asdfqwer/asdfxv

if [ $foo = */* ]
then
    echo bad
else
    echo good
fi

in test command, we could compare string and pattern like this,

[ string = pattern ]

[ string == pattern ]

however, the above script always print "good" in the terminal and also has error as below:

[ : asdfqwer/asdfxv : unexpected operator

Can someone tells me why and how to compare a stirng and a pattern in shell scripting?

2 Answers 2

2

The test command (or [ command), does not do globbed comparison. Instead, the shell is expanding the */* to match files in your directory, and substituting them in to that command. Presumably, one of the filenames gets parsed as an operator to the [ command, and is invalid.

The best way to compare against globs is case:

#!/bin/sh

foo=asdfqwer/asdfxv

case "$foo" in
   */*) echo bad ;;
   *) echo good ;;
esac
Sign up to request clarification or add additional context in comments.

Comments

0
if [ "$foo" == "*/*" ]
then
    echo bad
else
    echo good

You need double equals for comparison and looks like string comparisons require double quotes.

http://www.tech-recipes.com/rx/209/bournebash-shell-scripts-string-comparison/

2 Comments

I think it will not work since only foo=/ the result is bad. Otherwise, the result is good all the time
== is not POSIX compliant.

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.