Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am i getting an unexpected operator error in bash string equality test? [duplicate]

Tags:

bash

Where is the error on line four?

if [ $bn == README ]; then

which i still get if i write it as

if [ $bn == README ]
then

or

if [ "$bn" == "README" ]; then

Context:

for fi in  /etc/uwsgi/apps-available/* 
do 
        bn=`basename $fi .ini`
        if [ $bn == "README" ]
        then
                echo "~ ***#*** ~"
        else
                echo "## Shortend for convience ##"
        fi
done
like image 759
John Hall Avatar asked Aug 07 '13 11:08

John Hall


People also ask

Is not equal to in bash?

The not equal function in Ubuntu bash is denoted by the symbol “-ne,” which would be the initial character of “not equal.” Also included is the “! =” operator that is used to indicate the not equal condition.

What is ${ 2 in bash?

$2 is the second command-line argument passed to the shell script or function.

What is equal in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings.

What is the difference between sh and bash?

bash is sh, but with more features and better syntax. Bash is “Bourne Again SHell”, and is an improvement of the sh (original Bourne shell). Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. sh is a shell command-line interpreter of Unix/Unix-like operating systems.


2 Answers

You can't use == for single bracket comparisons ([ ]). Use single = instead. Also you must quote the variables to prevent expansion.

if [ "$bn" = README ]; then

If you use [[ ]], that could apply and you wouldn't need to quote the first argument:

if [[ $bn == README ]]; then
like image 98
konsolebox Avatar answered Oct 12 '22 08:10

konsolebox


Add the following to the top of your script:

#! /bin/bash

In bash, == is the same as = when used inside of single brackets. This is, however, not portable. So you should explicitly tell the shell to use bash as the script's interpreter by putting #! /bin/bash at the top of the script.

Alternatively, do your string comparisons using =. Note that the == operator behaves differently when used inside of double-brackets than when inside of single-brackets (see the link).

like image 35
Christopher Neylan Avatar answered Oct 12 '22 09:10

Christopher Neylan