为什么这个 bash expr 命令不起作用?
我试图在 bash 脚本中增加一个变量,但它不起作用。这是我的代码:
#! /bin/bash
COUNTER=0
while [ $COUNTER -lt 5 ]
do
echo "i will add this line to file mycreation">>./myfile
COUNTER = `expr $COUNTER + 1`
done
COUNTER
赋值周围的引号是反引号。
我尝试用 $COUNTER
替换 COUNTER
,如下所示:
$COUNTER = `expr $COUNTER + 1`
但这并没有解决问题,并给了我以下错误:
line7: 0: command not found.
I am trying to increment a variable in a bash script and it is not working. Here is my code:
#! /bin/bash
COUNTER=0
while [ $COUNTER -lt 5 ]
do
echo "i will add this line to file mycreation">>./myfile
COUNTER = `expr $COUNTER + 1`
done
The quotes around the COUNTER
assignment are backticks.
I tried replacing COUNTER
with $COUNTER
like this:
$COUNTER = `expr $COUNTER + 1`
But that did not solve the problem and gave me the following error:
line7: 0: command not found.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如 @Cory 正确指出的那样,等号周围不应该有空格,否则 bash 会混淆
COUNTER
表示命令。偏离主题...
也就是说,您可以通过使用以下替代方案来避免 bash fork 子进程:
使用 bash 内置“let”命令:
或者,使用 bash C 风格表达式:
<前><代码>(( COUNTER++ ))
事实上,您的 while 循环可以写为:
分解错误消息
当您遇到错误时:
我的猜测是您在第 7 行看到的内容 bash 最终看到的是
0 = 1
并且由于 bash 语句通常采用command arg1 arg1 ...
的形式,bash 将其解释为运行命令0
,参数= 1
。因此错误消息:0:找不到命令
。当您删除等号周围的空格时,bash 最终解释的是:
这意味着不带参数运行命令
0=1
,因此错误0=1:找不到命令.
变量赋值应采用
VAR_NAME=VALUE
形式(不带$
),因此您应使用的语法是:bash 计算并最终解释为:
As @Cory rightly pointed out, there should not be spaces around the equal sign or else bash will confuse
COUNTER
for a command.going off-topic ...
That said, you could avoid having bash fork a subprocess by using the following alternatives:
Using the bash builtin 'let' command:
or, using bash c-style expression:
In fact, your while loop can be written as:
Breaking down the error message
When you were met with the error:
my guess is what you had on line 7 was
What bash ends up see is
0 = 1
and since bash statements are generally in the formcommand arg1 arg1 ...
, bash interprets it as run the command0
with arguments= 1
. Thus the error message :0: command not found
.When you removed the spaces around the equal sign, what bash ends up interpreting is:
which means run command
0=1
with no arguments, hence the error0=1: command not found
.Variable assignments should be in the form
VAR_NAME=VALUE
(without the$
), so the syntax you should be using is:which bash evaluates and eventually interpret as:
删除等号周围的空格:
Remove the spaces around the equals sign:
另一种方式。
Another way.