文件中的换行符 - windows,Linux和MAC

软件开发或者运维工程师,工作中的开发环境,测试环境和生产环境很有可能会不同,因此有一个要必须了解和注意的回车/换行符问题, 因为回车/换行符在Windows、Linux和MAC OS系统中各不相同。

回车/换行” 概念来源于打字机。 字打完一行后, 重新开始一行需要两个操作:回车(回到一行的最左边 CR,Carriage Return)和 换行(切换到下一个 LF,Line Feed)。

计算机操作系统应用了这个概念,不过不同的系统有不同的实现。当我们在键盘上敲击 return 键来到新的一行,具体到文件编码,不同之处如下:

  • windows 采用 CRLF, 字符即 “\r\n”
  • Linux 采用 LR, 字符即 “\n”
  • MAC早期采用 CR, 字符即 “\r”, 如今也是 “\n”

举个例子,在 Windows里面开发shell脚本,在Linux环境中运行时会出错。


[centos@localhost Downloads]$ ./test.sh 
bash: ./test.sh: /bin/bash^M: bad interpreter: No such file or directory

[centos@localhost Downloads]$ bash test.sh 
test.sh: line 2: $'\r': command not found
hello world
test.sh: line 4: $'\r': command not found

[centos@localhost ~]$ cat -e ~/Downloads/test.sh
#!/bin/bash^M$
^M$
echo "hello world"^M$
^M$

^M是字符 “\r”, $是字符即“\n”

这样的情况下需要对文件进行换行符转换, 例如常用的 dos2unix,unix2dos, 等等

[root@localhost centos]# yum install dos2unix
[root@localhost centos]# dos2unix /home/centos/Downloads/test.sh 
dos2unix: converting file /home/centos/Downloads/test.sh to Unix format ...
[root@localhost centos]# bash /home/centos/Downloads/test.sh
hello world

猜你喜欢

转载自blog.51cto.com/9483003/2486479
今日推荐