Debopam Parua
Debopam Parua

Reputation: 530

Unexpected Operator error in shell script

This is the shell code I am running:

#!bin/bash

while true
do
        req=$(curl http://localhost/devcalls/camerarequest.php)

        if [ "$req" == "1" ]
        then
                sudo bash /home/ckoy-admin/HAS_system/camera/cam.sh
        fi
done

and this is the error I get when I execute:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     1  100     1    0     0     56      0 --:--:-- --:--:-- --:--:--    58
CAM.sh: 7: [: 1: unexpected operator

Please let me know what is wrong here.

Upvotes: 22

Views: 61137

Answers (5)

phd
phd

Reputation: 95159

if [ "$req" = 1 ]

or even better

if [ "$req" -eq 1 ]

See the syntax and operators in man test.

Upvotes: 25

alonegame
alonegame

Reputation: 87

View shell:

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Aug 11 2021 /bin/sh -> dash

This problem occurs due to the incompatibility between dash and bash. There are two ways to solve it:

  (1): sudo dpkg-reconfigure dash select NO
Change the dash of ubuntu's default shell link to traditional bash
lrwxrwxrwx 1 root root 4 August 11 09:53 /bin/sh -> dash (before modification)
lrwxrwxrwx 1 root root 4 Aug 11 09:53 /bin/sh -> bash
This problem occurs due to the incompatibility between dash and bash. .

  (2): Change == to =: because the default judgment statement in dash is =. .
For specific dash and bash, you can use man to find out. .

Upvotes: 1

Rishiram K
Rishiram K

Reputation: 21

using bash run.sh instead of sh run.sh worked for me.

Upvotes: 2

M V Amal Krishnan
M V Amal Krishnan

Reputation: 17

if [ "expr n%2 -eq 0" ]

if [ "expr n%2=0" ]

or

if [ 'expr n%2=0' ]

if [ 'expr n%2 -eq 0' ]

you can use any 4 method above mentioned i have tried all other answers but including every thing inside the "" gave me the output

Upvotes: -1

Ali Nazari
Ali Nazari

Reputation: 1438

To compare INTEGER

if [ "$req" -eq 1 ]

To compare STRING

if [ "$req" = "string" ]

Upvotes: 20

Related Questions