0

I'm trying to test a simple if statement by running it from the command line but bash wont run it.

add a variable
~$ myVar = 23
run a conditional statement
~$ if [$myVar -eq 23] then echo "myVar is 23" fi

Bash wont run this, what am I missing here?

5

To declare a variable spaces matter:

myVar = 23

The following is missing semicolons and the spacing inside the brackets matters:

if [$myVar -eq 23] then echo "myVar is 23" fi

Should be:

myVar=23

And:

if [ $myVar -eq 23 ]; then echo "myVar is 23"; fi

Could also be written without semicolons if written on multiple lines:

if [ "$myVar" -eq 23 ]
   then
   echo '$myVar is' "$myVar"
fi

And it is usually suggested to use double quotes on variables.

Single quotes are used for literal strings.

This is also valid syntax with one semicolon:

if [ "$myVar" -eq 23 ]; then
   echo '$myVar is' "$myVar"
fi
  • nice one, works! so the semi colons should be placed where a line return would be in a script file? – Michael Coleman Dec 6 '14 at 3:08
  • @MichaelColeman semicolons are a sort of way to designate lines of code in a single line. See the update – jmunsch Dec 6 '14 at 3:10
  • ahh.. so the semi colons dont exactly relate to line returns in a script...? – Michael Coleman Dec 6 '14 at 3:16
  • line returns \r or \n newlines or \l linefeeds are all different things. Unix like scripting languages interpret or parse the semicolons as "hey this statement is done". As to why that is part of the syntax that is history on me. Another name would be that the semicolon is a special character, or a metacharacter. Newline characters \n are also used as part of the syntax, along with a handful of other special characters and reserved words. In bash I am able to type help or help if and it will give me the rundown on it. – jmunsch Dec 6 '14 at 3:26
  • help if is useful - it shows where semi-colons go, thanks – Michael Coleman Dec 6 '14 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.