Bash 错误:“第 8 行:[: 2:应为一元运算符”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36814380/
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 14:32:49  来源:igfitidea点击:

Bash error: "line 8: [: 2: unary operator expected"

bashshell

提问by ElenaD

Please help me with this error I received with a shell script in Bash: line 8: [: 2: unary operator expected

请帮助我解决我在 Bash 中使用 shell 脚本收到的错误: line 8: [: 2: unary operator expected

#!/bin/bash

echo "Input your number for factorial calculation: "
read $nr

counter=2
factorial=1

while [ $counter -le $nr ]
do
 factorial=$(( $factorial * $counter ))
 counter=$(( $counter + 1 ))
done

echo "The result " $nr "! is:"
echo $factorial

Something is wrong with the while line. Maybe the $nris not used correctly?

while 行出了点问题。也许$nr没有正确使用?

回答by gudok

readtakes nameof the variable, not its value. You need to replace read $nrwith read nr.

read获取变量的名称,而不是它的值。您需要替换read $nrread nr.

回答by Mort

You seem to be having trouble formatting your question, so I cannot see it, but generally you get that error if you have something like if [ $a -ne $b ]but one of $aor $bis empty, so basically the interpreter sees something like if [ -ne $b ]. They ways to avoid it are either

您似乎在格式化您的问题时遇到问题,所以我看不到它,但通常如果您有类似if [ $a -ne $b ]但其中之一$a$b为空的内容,您会收到该错误,因此基本上解释器会看到类似if [ -ne $b ]. 他们避免它的方法是

  1. Ensure that the variables are set before such a test, or
  2. Quote the variables, so even an empty or undefined one will be seen as an empty string. Although at this point you can only use string, not numerical comparison. if [ "$a" != "$b" ]
  1. 确保在此类测试之前设置变量,或
  2. 引用变量,因此即使是空的或未定义的变量也将被视为空字符串。虽然此时您只能使用字符串,而不是数字比较。if [ "$a" != "$b" ]