dos2unix unix2dos se ff=unix

网友投稿 762 2022-09-22

dos2unix unix2dos se ff=unix

dos2unix  unix2dos  se ff=unix

问题及解决方案

在windwos下用记事本编写了个shell脚本,拿到cygwin下运行没问题,但是

拿到linux下运行就出问题,显示:

:bad interpreter:no such file or directory

出现问题的原因就是“行终束符”,unix/linux使用 换行符;而dos/windows使

用 回车+换行

解决办法:

1.使用vi打开该脚本

2.设置fileformat(ff)

:set ff=unix

3.另存

:w test.sh

此时test.sh就能在linux下执行了(运行前注意是否可执行)

注:在cygwin下fileformat为unix或dos都可以

示例一 DOS格式文本文件在Linux下的表现

现在有一个脚本文件job.sh,是在Linux下用vi编辑的。

[root@jfht ~]# cat job.sh

#!/bin/sh

date >job.txt

现在把它转换成DOS格式文本文件。

[root@jfht ~]# unix2dos job.sh

unix2dos: converting file job.sh to DOS format ...

尝试着运行一下。

[root@jfht ~]# ./job.sh

-bash: ./job.sh: 权限不够

[root@jfht ~]# chmod +x job.sh

[root@jfht ~]# ./job.sh

-bash: ./job.sh: /bin/sh^M: bad interpreter: 没有那个文件或目录

DOS格式的脚本文件时无法解释执行的,因为脚本文件的第一行是用来指定解释

器的,Linux系统认为解释器是/bin/sh^M,而不是/bin/sh。

我们来通过Linux下的一些命令来看一下DOS格式文件的真面目。

[root@jfht ~]# cat -v job.sh     <== cat -v可以看到文件中的非打印字符

,而不带-v参数的cat命令不行。

#!/bin/sh^M

^M

date >job.txt^M

^M

[root@jfht ~]# hexdump -C job.sh       <== hexdump -C可以看到文件每个

字节的十六进制表示。

00000000  23 21 2f 62 69 6e 2f 73  68 0d 0a 0d 0a 64 61 74  |

#!/bin/sh....dat|

00000010  65 20 3e 6a 6f 62 2e 74  78 74 0d 0a 0d 0a         |e

>job.txt....|

0000001e

[root@jfht ~]# vi job.sh     <== 使用vi打开时可以看到底下有[dos]的格

式提示。有些版本vi显示的是行尾为^M。

#!/bin/sh

date >job.txt

~

~

"job.sh" [dos ] 4L, 30C

现在我们把DOS格式改回Unix格式的,看看效果。

root@jfht ~]# dos2unix job.sh

dos2unix: converting file job.sh to UNIX format ...

[root@jfht ~]# ./job.sh

可以执行了,不再报“-bash: ./job.sh: /bin/sh^M: bad interpreter: 没有

那个文件或目录”这个错了。

[root@jfht ~]#

示例二 dos2unix -k和dos2unix -n的使用示例

[root@jfht ~]# cat <1.txt

> 1

> 2

> 3

> EOF

[root@jfht ~]# file 1.txt

1.txt: ASCII text

[root@jfht ~]# ls -l 1.txt

-rw-r--r-- 1 root root 6 11-14 09:08 1.txt

[root@jfht ~]# date

2010年 11月 14日 星期日 09:28:42 CST

[root@jfht ~]# unix2dos -k 1.txt      <== 保持文件时间戳

unix2dos: converting file 1.txt to DOS format ...

[root@jfht ~]# ls -l 1.txt

-rw-r--r-- 1 root root 9 11-14 09:08 1.txt

[root@jfht ~]# dos2unix -n 1.txt 2.txt     <== 将1.txt转换到2.txt

dos2unix: converting file 1.txt to file 2.txt in UNIX format ...

[root@jfht ~]# ls -l 1.txt 2.txt

-rw-r--r-- 1 root root 9 11-14 09:08 1.txt

-rw-r--r-- 1 root root 6 11-14 09:30 2.txt

[root@jfht ~]# file 1.txt 2.txt

1.txt: ASCII text, with CRLF line terminators

2.txt: ASCII text

[root@jfht ~]# cat -v 1.txt

1^M

2^M

3^M

[root@jfht ~]# cat -v 2.txt

1

2

3

[root@jfht ~]#

注意:dos2unix 而不是 unix2unix

记得用 rpm -qf `which dos2unix`  查看安装包

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:部队->运维->分享->讲师历程
下一篇:C# 命名规则(cctv5体育节目表)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~