我从来没有在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
Run Code Online (Sandbox Code Playgroud)
而这个错误:
/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
Run Code Online (Sandbox Code Playgroud)
我想比较我的数组的相邻值并存储它们之间的最小差异...但我不知道如何在bash中执行If语句
Wil*_*ell 18
每个命令必须通过换行符或分号正确终止.在这种情况下,您需要将分配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
Run Code Online (Sandbox Code Playgroud)
此外,您需要使用lt而不是<,因为<是重定向运算符.(除非您打算运行以$tmp变量命名的文件的输入命名的命令$result)
正如其他人所指出的那样,你缺少一个分号而需要使用-lt而不是代替<.
if声明的替代方法是使用逻辑和运算符&&:
for (( i=0; i<N-1; i++ )); do
tmp=$(( sorted_array[i+1] - sorted_array[i] ))
[ $tmp -lt $result ] && result=$tmp
done
Run Code Online (Sandbox Code Playgroud)