1

So I have this bash script

function exec_do(){
while [[ 1 ]]; do
  read _INPUT
  if [$_INPUT -eq "exit"]
  then
    break
  else
    echo $_INPUT
  fi
done
}

The intention is so that if I type in exec_do then it does a while loop which reads the input and do stuff based on the input.

If the input is exit, then it exits the while loop

If the input is not exit then it echoes it

However when I run exec_do and then type in input It instead returns input: command not found And moreover typing in "exit" doesn't break the loop and also return command not found

What did I do wrong and how can I fix this?

1 Answer 1

3

Your comparison for _$INPUT is a string, then you need ==. If comparing integers, you need -eq. Also double quote the $_INPUT variable for strings if they might contain white spaces or meta characters.

#!/bin/bash  

function exec_do(){ 
  while [[ 1 ]]; do  
    read _INPUT
    if[ "$_INPUT" == "exit" ]; then
      break
    else
      echo $_INPUT
    fi 
  done
  }

exec_do
Sign up to request clarification or add additional context in comments.

2 Comments

Good fix, especially if bash will always be the shell that runs the script. If portability for simpler/older shells is ever needed (ash or ksh, say), older syntax may be needed: [ ] instead of [[ ]], no function keyword, = instead of ==.
Since the OP has bash as a tag for his question, I assume he is using only that shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.