Bash 中的“[0:找不到命令”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42558479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:50:46  来源:igfitidea点击:

"[0: command not found" in Bash

bashshellsyntax

提问by Dhaval Babu

I am trying to get the array in the while-loop and need to update the value in array too.

我试图在 while 循环中获取数组,并且也需要更新数组中的值。

Below is my code what I have tried. I get this error [0: command not found

下面是我尝试过的代码。我收到这个错误[0: command not found

#!/bin/bash
i=0
while [$i -le "{#myarray[@]}" ]
do 
    echo "Welcome $i times"
    i= $(($i+1)))
done

How do I fix this?

我该如何解决?

回答by codeforester

Need a space after [and no space before or after =in the assignment. $(($i+1)))would try to execute the output of the ((...))expression and I am sure that's not what you want. Also, you are missing a $before the array name.

分配后需要一个空格,前后[没有空格=$(($i+1)))会尝试执行((...))表达式的输出,我确定这不是您想要的。此外,您$在数组名称之前缺少一个。

With these things corrected, your while loop would be:

纠正这些事情后,您的 while 循环将是:

#!/bin/bash
i=0
while [ "$i" -le "${#myarray[@]}" ]
do 
  echo "Welcome $i times"
  i=$((i + 1))
done
  • i=$((i + 1))can also be written as ((i++))
  • it is always better to enclose variables in double quotes inside [ ... ]
  • check your script through shellcheck- you can catch most basic issues there
  • i=$((i + 1))也可以写成 ((i++))
  • 将变量用双引号括起来总是更好 [ ... ]
  • 通过shellcheck检查您的脚本- 您可以在那里发现最基本的问题


See also:

也可以看看: