shell 脚本中出现意外的操作员错误

问题描述 投票:0回答:5

这是我正在运行的 shell 代码:

#!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

这是我执行时遇到的错误:

  % 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

请让我知道这里出了什么问题。

bash shell
5个回答
22
投票
if [ "$req" = 1 ]

甚至更好

if [ "$req" -eq 1 ]

请参阅man test中的语法和运算符。


18
投票

比较 INTEGER

if [ "$req" -eq 1 ]

比较STRING

if [ "$req" = "string" ]

1
投票

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

if [ "expr n%2=0" ]

if [ 'expr n%2=0' ]

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

你可以使用上面提到的任何4种方法,我已经尝试了所有其他答案,但包括“”内的所有内容给了我输出


1
投票

使用

bash run.sh
而不是
sh run.sh
对我有用。


1
投票

查看外壳:

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

出现这个问题是因为dash和bash不兼容。有两种方法可以解决:

  (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. .

© www.soinside.com 2019 - 2024. All rights reserved.