Search code examples
bashfunctionline-endings

Function not working in a bash script - error messages relate to '\r'


I have recently installed a fresh version of Debian. I created this simple script:

#!/bin/bash

print_something () {
  echo Hello I am a function
}

print_something
print_something

However this displays this error upon me issuing bash test.sh:

test.sh: line 3: $'\r': command not found
test.sh: line 4: syntax error near unexpected token `$'{\r''
'est.sh: line 4: `print_something () {

What am I doing wrong? Many thanks!


Solution

  • Diagnosing:

    • Unix utilities in general expect line endings to be \n only, and usually break or show unexpected behavior and output with files that have Windows-style \r\n line endings - as bash does here.
    • Error messages containing the string \r are an indicator that such Windows-style line endings are present.
    • Passing a file to cat -v and examining the output for ^M at the end of output lines (which is how \r chars. are represented) is a way to check a file for Windows-style line endings on demand.

    Fixing:

    • To convert a file with Windows-style line endings to Unix-style ones:
      • use the dos2unix utility, if already installed (typically, it is not), or installing it is an option; how you install it depends on your platform; e.g.:
        • on Ubuntu: sudo apt-get install dos2unix
        • on OSX, with Homebrew installed, brew install dos2unix
      • alternatively, use standard utilities to perform the conversion; there are several options; e.g.:
        • sed $'s/\r$//' win.txt > unix.txt
        • awk 'sub("\r$", "")+1' win.txt > unix.txt
        • There are variants of the above commands that update a file in place, but they're platform-specific, if available at all.
    • Make sure that the editor you use to create shell scripts / files for use with Unix utilities is configured to use Unix-style line endings.