bash - 函数在 bash 脚本中不起作用 - 错误消息与 '\r' 相关

标签 bash function line-endings

我最近安装了新版本的 Debian。我创建了这个简单的脚本:

#!/bin/bash

print_something () {
  echo Hello I am a function
}

print_something
print_something

但是,当我发出 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 () {

我做错了什么? 非常感谢!

最佳答案

诊断:

  • Unix 实用程序通常只希望行结尾为 \n,并且通常会破坏或显示具有 Windows 样式 \r\n 的文件的意外行为和输出行结尾 - 正如 bash 在这里所做的那样。
  • 包含字符串 \r 的错误消息表明存在此类 Windows 样式的行结尾。
  • 将文件传递给 cat -v 并在输出行末尾检查 ^M 的输出(这就是 \r字符。表示)是一种按需检查文件中 Windows 样式行结尾的方法。

修复:

  • 要将 Windows 风格的行结尾转换为 Unix 风格的文件:
    • 使用dos2unix实用程序,如果已安装(通常),或者可以选择安装它;如何安装取决于您的平台;例如。:
      • 在 Ubuntu 上:sudo apt-get install dos2unix
      • 在 OSX 上,带有 Homebrew已安装,brew install dos2unix
    • 或者,使用标准实用程序来执行转换;有多种选择;例如。:
      • sed $'s/\r$//' win.txt > unix.txt
      • awk 'sub("\r$", "")+1' win.txt > unix.txt
      • 上述命令有多种就地更新文件的命令,但它们特定于平台(如果有的话)。
  • 确保您用来创建与 Unix 实用程序一起使用的 shell 脚本/文件的编辑器配置为使用 Unix 样式的行结尾。

关于bash - 函数在 bash 脚本中不起作用 - 错误消息与 '\r' 相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151725/

相关文章:

bash - 如何将php(及其stderr)中的exec调用的输出重定向到调用程序?

linux - 比较 2 个文件时进行 Bash shell 脚本检查

bash - 快速 ls 命令

function - 将函数存储在 unix 变量中

sublimetext3 - 崇高文本 : Change line endings of all files in a project

bash - 在 MacOS 和 Linux 上运行不同的 Shell 脚本

javascript - 在 JavaScript 中禁用文本选择器

c++ - 我能知道我的函数有多少个参数吗?

windows - 使用 EditorConfig 会影响我应该如何为行尾配置 Git 吗?

vim - 如何制作vim :source accept different line endings?