Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line if statement in bash

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

like image 809
RagnaRock Avatar asked Jun 29 '15 14:06

RagnaRock


People also ask

How do you write an if statement in one line 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 ]”).

Is 1 true or false in bash?

However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs.

What does $() mean in bash?

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).

What is $_ in bash?

$_ (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.


2 Answers

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)

like image 124
William Pursell Avatar answered Oct 18 '22 22:10

William Pursell


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
like image 9
hek2mgl Avatar answered Oct 19 '22 00:10

hek2mgl