bash file returns unexpected token `$'do\r''

This worked for me:

dos2unix my_script.sh

If you don't have dos2unix :

For CentOS, Fedora or RHEL:

$ sudo yum install dos2unix

For Ubuntu or Debian:

$ sudo apt-get install tofrodos
$ sudo ln -s /usr/bin/fromdos /usr/bin/dos2unix 

Explanation

This commonly is caused when the executable file is created in an operative system (windows) and used in another operative system (Linux). Also rare text editors could be the problem.


Another possible solution using unix text editor vi:

open file in vi edit with vi filename.sh command;

type in vi :set ff=unix command;

save file with :wq

It will save the file with unix line endings.


Your script has been edited on a DOS or Windows based system and contains carriage-return characters that Linux/Unix does not like (that what \r is). You could use dos2unix to convert the carriage return line endings to the correct format; if you don't have dos2unix you might use awk like

awk '{ sub("\r$", ""); print }' git-copy.sh > git-copy2.sh
mv git-copy2.sh git-copy.sh

Just change your line sequence in your text editor from CRLF to LF. It worked for me :)

for notepad++ : edit => EOL Conversion => Unix(LF)

Tags:

Bash