• Uncategorized

About bash : Equality-test-in-if-command-returning-the-error-message-no-such-file-or-directory

Question Detail

I’m writing a shell script and I’m doing

if ["$item0" == "$item1"]
then
echo match
fi

but it’s giving the error message “No such file or directory” on the line when run. The items above do contain file paths if that helps.

Question Answer

You need to note the spaces for between variables and the brackets, they matter. Also if then is on the same line as if, you need a ;

Corrected syntax:

if [ "$item0" == "$item1" ]; then
    echo match
fi

P.S. if match is supposed to be a variable, make sure it’s echo "$match"

To begin, when posting here you should probably always give the full error messages, possibly removing any sensitive data.

Let’s begin by explaining how your line is wrong, first:

  1. In bash, [ is basically a synonym for test, with a few minor differences (the most noticeable one is that it expects its last argument to be ]). Run man test for more info. test takes in stuff with its own syntax, then returns a proper value depending on whether its input evaluated to true or false. So, since test is a program, and not a bash build-in, it must take it’s inputs as separate parameters (note the spaces):

    [ "$item0" = "$item1" ]

    The = instead of the == is a stylistic preference. They do the same thing, but = is preferred by some people since bash is not C.

  2. Second, bash needs to know when the input to an external command ends. This is done with ;. To make this clearer, suppose I do this

    if true then echo foo fi fi

    Now I’m trying to print out foo fi if the if statement evaluates to true. See my problem? Bash doesn’t know when to terminate the input to your echo command.

Properly rewritten:

if [ "$item0" = "$item1" ]; then echo match; fi

For what it’s worth, if you’re using bash, [[ is a lot easier to use and more reliable than [ (unless you really need portability, [[ has for some time been the preferred bash idiom). For one thing, it’s not necessary to quote parameter expansions with [[, and you also don’t have to worry about empty strings. It also features both pattern matching (with ==) and regex matching (with =~).

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.