【问题标题】:One line if statement in bashbash中的一行if语句
【发布时间】:2015-06-29 14:49:10
【问题描述】:

我从未在 bash 中编程...但我正在尝试解决游戏中的成就问题 (codingame.com)

我有以下代码:

for (( i=0; i<N-1; i++ )); do
   tmp=$(( sorted_array[i+1] - sorted_array[i] ));
   if [ $tmp < $result ]; then result=$tmp fi
done

还有这个错误:

/tmp/Answer.sh: line 42: syntax error near unexpected token `done'at Answer.sh. on line 42
/tmp/Answer.sh: line 42: `done' at Answer.sh. on line 42

我想比较我的数组的相邻值并存储它们之间的最小差异......但我不知道如何在 bash 中执行 If 语句

【问题讨论】:

  • 通过shellcheck.net 运行此程序将捕获一些项目,就此而言,这里的人们没有。
  • 请注意 -- if (( tmp &lt; result )); then result=$tmp; fi 也是一个选项,它消除了 -lt&lt; 的问题,引用的可能性。

标签: bash if-statement


【解决方案1】:

每个命令都必须以换行符或分号正确终止。在这种情况下,您需要将result 的分配与关键字fi 分开。尝试添加分号;

for (( i=0; i<N-1; i++ )); do
   tmp=$(( sorted_array[i+1] - sorted_array[i] ))
   if [ "$tmp" -lt "$result" ]; then result=$tmp; fi
done

此外,您需要使用lt 而不是&lt;,因为&lt; 是一个重定向运算符。 (除非您打算使用来自变量 $result 的文件的输入来运行名为 $tmp 的命令)

【讨论】:

  • 命令需要用分号分隔,不能以分号结尾。
  • 分离标记用于终止解析器中的命令。
  • 分号表示语句的结束,它不会终止任何内容。
  • 好吧,那它终止一个语句,你现在是在和自己争论吗??
  • @ikegami 别在这里做一个迂腐的傻瓜!修正你自己的答案,因为它实际上是错误的。
【解决方案2】:

正如其他人指出的那样,您缺少分号,需要使用 -lt 而不是 &lt;

if 语句的替代方法是使用逻辑 and 运算符&amp;&amp;:

for (( i=0; i<N-1; i++ )); do
   tmp=$(( sorted_array[i+1] - sorted_array[i] ))
   [ $tmp -lt $result ] && result=$tmp
done

【讨论】:

  • @User112638726 你以为如果有人问“我怎么跳出窗外”我不能回答“请不要这样做! "?是否明确表示:Read the question carefully. What, specifically, is the question asking for? Make sure your answer provides that – or a viable alternative.。在投反对票和/或评论帖子之前,请阅读常见问题解答。
  • @User112638726 常见问题解答链接:stackoverflow.com/help/how-to-answer .. 你确实做了破坏行为,我已经标记了。
  • 糟糕的类比,他们没有做任何危险的事情。您刚刚发布了与已接受的答案相同的答案,并添加了一个毫无意义的 &&,这只会损害可读性。
  • 所以你认为test &amp;&amp; cmd 不是bash 中单行if 语句的单一命令的可行替代方案?常见的!讨论结束。
【解决方案3】:

您的if 后面需要跟fi 命令,但您没有任何此类命令。您的代码中有一个fi,但它位于另一个命令的中间,因此它不再完成if,然后echo fi 中的fi 将完成。如果要将行合并在一起,则需要使用分号来分隔命令。

所以要崩溃

for (( i=0; i<N-1; i++ ))
do
   tmp=$(( sorted_array[i+1] - sorted_array[i] ))
   if [ $tmp -lt $result ]
   then 
      result=$tmp
   fi
done

你会使用

for (( i=0; i<N-1; i++ )); do
   tmp=$(( sorted_array[i+1] - sorted_array[i] ))
   if [ $tmp -lt $result ]; then result=$tmp; fi
done
  • 例外:dothen 可以后跟命令,因此在下一行合并时不需要在它们后面加分号。

  • 注意您不需要用; 终止命令吗? ; 仅在命令之间需要。

  • test ([]) 内部,-lt 用于比较数字。

【讨论】:

  • 您可能希望使用算术运算符进行比较-lt
  • @User112638726,已修复。
猜你喜欢
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
相关资源
最近更新 更多