Home > Blockchain >  Syntax error in conditional expression and near `then' in Ubuntu terminal
Syntax error in conditional expression and near `then' in Ubuntu terminal

Time:05-13

I'm just learning terminal commands, I'm trying to create my own command, but I have the following problem

 ./myFile: line 10: syntax error in conditional expression
 ./myFile: line 11: syntax error near `then'
 ./myFile: line 11: `    then'

there is my code

#!/bin/bash
echo "please enter name of the folder"
read NAME1

if [[ $NAME1 ]]  
then
  echo "enter first number"
  read NUM1

  if [[ $NUM1 ]] && [[ $NUM1 -ge 0]] 
  then
    echo "enter last number"
    read NUM2

    if [[ $NUM2 ]] && [[ $NUM2 -gt $NUM ]]  
    then
      mkdir $NAME1{$NUM1..$NUM2}
    else
      echo"please enter last number to continue"
    fi
  else
    echo "please enter first number to continue"
  fi

else
  echo "please enter name of the folder to continue"
fi

CodePudding user response:

Firstly, the expression [[ $NAME1 ]] is not valid, or at least, does not do what you think it does. I believe you are trying to determine if the user actually typed in a string. To do this, you should either test for a non-empty string ([[ -n ${NAME1} ]]) or test for a string length greater than zero ([[ ${#NAME1} -gt 0 ]]). The same applies when you are testing $NUM1 and $NUM2.

Secondly, when dealing with user input, you should take care to avoid testing empty strings. This is best achieved by quoting your variables. For example: [[ "${NUM1}" -gt 0 ]].

Thirdly, spaces are important in tests. always leave a space after the [[ and before the ]].

In addition, $NUM (line 15) is not declared, so will evaluate to the empty string. This should be set somewhere earlier in the script.

There are many other areas in which this script could be improved (e.g. checking for numerical input, checking for valid folder names, etc. But the above changes should get you past the immediate errors.

  •  Tags:  
  • bash
  • Related