0

The following while loop is designed to keep asking for user input until a specified 'break' character is entered. However, for some reason this IF statement appears to be triggered regardless of what text is entered.

 while true; do
    #Prompt user for Input
    printf "Please insert value. Insert the letter 'D' when you are done\n";
    #Read User Input
    read User_Input;
    echo "DEBUG: Input is: $User_Input";
    #Check User Input for Break Command
        if [ "$User_Input"=="D" ]; then
            break
        fi

done

Further up in the script I have the user input variable declared as User_Input="";

As far as I can tell the if statement is correct and the script is not throwing any errors when run.

RedBullNinja
  • 135
  • 5
  • If you read [the Bash manual page](http://man7.org/linux/man-pages/man1/bash.1.html) you will see that the `==` operator is a Bash-specific extension used for double-bracketed expressions (i.e. in `[[ ... ]]`). For single-bracket you should read [the `test` manual page](http://man7.org/linux/man-pages/man1/test.1.html). – Some programmer dude Oct 13 '17 at 09:51

2 Answers2

3
if [ "$User_Input"=="D" ]; then

DEBUG: Input is: a
+ '[' a==D ']'
+ break

should be written as

if [ "$User_Input" == "D" ]; then

DEBUG: Input is: e
+ '[' e == D ']'
+ true
+ printf 'Please insert value. Insert the letter '\''D'\'' when you are done\n'
Please insert value. Insert the letter 'D' when you are done
+ read User_Input
D
+ echo 'DEBUG: Input is: D'
DEBUG: Input is: D
+ '[' D == D ']'
+ break

Spaces are needed before and after the ==

Srini V
  • 11,045
  • 14
  • 66
  • 89
2

From

if [ "$User_Input"=="D" ]; then

To

# space
if [ "$User_Input" == "D" ]; then

Because it invokes the command [ with 4 arguments.

As the man page for bash builtins states: "Each operator and operand must be a separate argument."

Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36