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

穿精又带淫゛_ 提交于 2019-12-11 02:54:37

问题


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!


回答1:


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.



回答2:


I resolved the issue by installing dos2unix and then converting the file. Many thanks to mklement0 who pointed this out.



来源:https://stackoverflow.com/questions/30151725/function-not-working-in-a-bash-script-error-messages-relate-to-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!