插件窝 干货文章 linux的换行符是什么

linux的换行符是什么

换行符 转为 Linux Unix 353    来源:    2025-04-14

在Linux系统中,换行符(Line Ending)使用 LF(Line Feed) 字符表示,对应的ASCII码是 \n(即 0x0A)。这是Linux/Unix系统的标准换行符。

关键点总结:

  1. Linux/Unix\n(LF)

    • 示例:Hello\nWorld
  2. Windows\r\n(CRLF)

    • 回车(Carriage Return, \r,ASCII 0x0D) + 换行(\n)。
    • 示例:Hello\r\nWorld
  3. 经典Mac(OS X之前)\r(CR)

    • 现代macOS(基于Unix)已改用\n,与Linux一致。

常见问题与处理:

  1. 文件换行符转换

    • 使用 dos2unix(Windows转Linux)或 unix2dos(Linux转Windows)工具:
      bash dos2unix filename # 将CRLF转为LF unix2dos filename # 将LF转为CRLF
    • 或用 sed 命令删除 \r
      bash sed -i 's/\r//g' filename
  2. Git自动处理换行符
    在Git中设置核心配置,避免跨平台协作问题:

    git config --global core.autocrlf input  # Linux/macOS用户(提交时转为LF)
    git config --global core.autocrlf true   # Windows用户(检出时转为CRLF,提交时转为LF)
    
  3. 文本编辑器显示

    • 在Vim中查看换行符类型:
      vim :set ff? 输出可能是 fileformat=unix(LF)、dos(CRLF)或 mac(CR)。

为什么重要?

  • 脚本执行问题:如果Shell脚本包含\r,可能导致错误(如 ^Mbad interpreter)。
  • 跨平台开发:混合换行符会导致代码差异(如Git显示整个文件被修改)。

通过工具或配置统一换行符,可以避免这些问题。