I've never programed in bash... yet I'm trying to solve a problem for an anchievement in a game (codingame.com)
I have the following code:
for (( i=0; i<N-1; i++ )); do
tmp=$(( sorted_array[i+1] - sorted_array[i] ));
if [ $tmp < $result ]; then result=$tmp fi
done
And this error:
/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
I want to compare adjacent values of my array and store the minimun diference between them... but I cant figure how to do an If statement in bash
The syntax of an bash if statement A short explanation of the example: first we check if the file somefile is readable (“if [ -r somefile ]”). If so, we read it into a variable. If not, we check if it actually exists (“elif [ -f somefile ]”).
However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs.
Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
Each command must be properly terminated, either by a newline or a semi-colon. In this case, you need to separate the assignment of result
from the keyword fi
. Try adding a semi-colon;
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
Also, you need to use lt
rather than <
, since <
is a redirection operator. (Unless you intend to run a command named $tmp
with input from a file named by the variable $result
)
You are missing a semicolon and need to use -lt
instead of <
, as others pointed out.
An alternative to the if
statement would be to use the logical and operator &&
:
for (( i=0; i<N-1; i++ )); do
tmp=$(( sorted_array[i+1] - sorted_array[i] ))
[ $tmp -lt $result ] && result=$tmp
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With