Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a shell script giving syntax errors when the same code works elsewhere? [duplicate]

I have a simple shell script I copied from a working script. It works if I copy-paste it to a terminal:

if true
then
  true
fi 

However, when I run the script with bash myscript, I get various syntax errors as if some of the keywords are missing.

  • myscript: line 4: syntax error near unexpected token `fi' , as if then isn't there.
  • myscript: line 6: syntax error: unexpected end of file , as if fi isn't there.
  • myscript: line 4: syntax error near unexpected token `$'\r' .. what?

Why does this happen in this particular script, but not on my command line or in the script I copied from?

like image 766
that other guy Avatar asked Aug 07 '15 20:08

that other guy


People also ask

What is &2 in shell script?

and >&2 means send the output to STDERR, So it will print the message as an error on the console. You can understand more about shell redirecting from those references: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections.

How do I run the same script multiple times in Linux?

Run a Command Multiple Times in Linux using a while Loop In the above format, i represents the counter variable, [ $i -le n ] is the test condition and n is the number of times you wish to run the command (ideally the number of times the shell will iterate through the loop.

How can I run two shell scripts at the same time?

That said, if all you need to do is run the scripts in parallel and wait for them to complete, you can do something like ./script.sh 1 & ./script.sh 2 & ./script.sh 3 & ./script.sh 4 & wait in your script.


1 Answers

TL;DR: Your script has Windows style CRLF line endings, aka \r\n.

Convert to Unix style \n by deleting the carriage returns.


How do I check if my script has carriage returns?

They're detectable as ^M in the output of cat -v yourscript:

$ cat -v myscript
if true^M
then^M
  true^M
...

How do I remove them?

Set your editor to save the file with Unix line endings, aka "line terminators" or "end-of-line characters", and resave it.

You can also remove them from a command line with dos2unix yourscript or cat yourscript | tr -d '\r' > fixedscript.

Why do carriage returns cause syntax errors?

The carriage return character is just another character to bash. then is not the same as then\r, so bash doesn't recognize it as a keyword and assumes it's a command. It then keeps looking for a then and fails

If there happens to be a trailing space after then, you get a similar problem for fi.

like image 81
that other guy Avatar answered Oct 02 '22 05:10

that other guy