温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

dos2unix unix2dos se ff=uni

发布时间:2020-02-28 20:15:14 来源:网络 阅读:828 作者:冷暖己知 栏目:系统运维

  问题及解决方案  


   在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 <<EOF >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`  查看安装包


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI