How Do You Troubleshoot the Bash Script Error “line 5: $’\r’: command not found”?

Problem scenario
You drafted a Bash script on a Windows computer.  You then uploaded it to Google Cloud Platform via a web browser feature.  When you run the bash script on a Linux server (e.g., in GCP), you get this error "line 5: $'\r': command not found".  You do not want to install dos2unix or any new packages.  What should you do?

Solution
The file needs to be modified or "cleaned up."  Special characters were introduced with the way it was transferred over to the Linux system.  Assuming the file is called foo.txt, run this command:

perl -p -i -e "s/\r//g" foo.txt

Leave a comment

Your email address will not be published. Required fields are marked *