Home > Software engineering >  How to use if then in bash
How to use if then in bash

Time:01-29

We have a text file with 4 lines and a different number of words and i want to count the words per line and see if the number is even or odd but the result keeps saying

./oddwords.sh: line 14: syntax error near unexpected token `then'
./oddwords.sh: line 14: `  if[ n % 2 == 0 ]; then'

This is what ive done so far

#!/bin/bash
if [ $# -ne 1 ] ; then
{
  echo "Wrong number of arguments!"
  exit 1
}
fi



while read line ; do
n= echo "$(echo $line | wc -w)"
if[ n % 2 == 0 ]; then
  echo "Is even"
 else
  echo "Is odd"
fi

done < $1

CodePudding user response:

Using double brackets like if [[ n % 2 == 0 ]]; then and making the numbers variables at the top instead of just saying 2

a=2
b=1

at the beginning then referencing them later in the if statement like if [[ $a%2 == 0 ]]; then

if you still have issues try if [[ $a%2 -eq 0 ]]; then

Here are a couple sites i find useful for checking bash when I get stuck on something as well.

https://www.shellcheck.net/

https://explainshell.com/

  • Related