Why is there an unexpected token in Bash?

Why is there an unexpected token in Bash?

The one-liner that was failing with an error contains the then statement that as you can see is not part of the structure of a for loop. There is a syntax error. The token ‘ then ‘ is unexpected. All good!

What to do if you get syntax error near unexpected token?

If you get that error, you may have bad line endings. Unix uses at the end of the file while Windows uses . That character gets interpreted as a character. You can use od -a test.sh to see the invisible characters in the file.

Why do I get an unexpected syntax error in Bash?

Sometimes this error happens because of unexpected CR characters in file, usually because the file was generated on a Windows system which uses CR line endings. You can fix this by running os2unix or tr, for example:

How to fix syntax error in one command?

To fix the error in a single command it’s usually enough to add or remove some incorrect characters that cause the syntax error in the command. Knowing how to fix the error in a script can take a bit more time, and for that I will use the following 5-step process: Run the script that contains the syntax error.

Where does the syntax error come from in Bash?

For instance, if there’s a file called 2 in the current directory, that becomes: That is run the 2 command with 4 arguments: 2, then, echo and fi, as the first command in the if part of an if/then/elif/else/fi statement. The error comes from that second ; on the second line.

Why is there an unexpected token error in Notepad?

I guess an encoding issue is less likely given you are using a MAC than if you had used a Windows text editor, however I think file encoding is still worth considering. In this case, Notepad saved the file with carriage returns and linefeeds, causing the error shown above.

What to do when you get syntax error in Bash?

Lesson 3: When you see a syntax error verify that you are using Bash loops or conditional constructs in the right way and you are not adding any statements that shouldn’t be there. I have created a simple script in which an if statement is nested inside a while loop.