记录一次sh脚本windows可以运行但是linux报错 unexpected (expecting “do“)

编辑一个sh脚本,在windows测试没有问题,可以正常运行

脚本内容如下

#!/bin/sh

clean() {
  for file in $1/*
  do
	if [ -d $file ]
	then
	  clean $file
	else
	  echo $file
	  temp=$(tail -100 $file)
	  echo "$temp" > $file
	fi
  done
}

dir=logs
clean $dir

在windows环境运行如下

tyj@LAPTOP-RG7JRG0D MINGW64 /g
$ sh clean.sh
logs/a.log
logs/b.log
logs/clean.sh

但是把代码放在linux环境运行就出现问题了,报错如下

root@6f240fe0cafa:/code# sh clean.sh
: not found:
clean.sh: 5: Syntax error: word unexpected (expecting "do")

很奇怪同样的脚本为什么能在windows环境可以运行,但是linux就有问题,我通过下面命令查看了文件(clean.sh是我的文件名),结果发现了问题,显示如下,多了很多^M,这个是Windows的换行,所以在Linux中执行脚本会失败。而在Windows中可以识别这些换行,所以在Windows中可以正常执行脚本。

cat -v clean.sh
[root@VM-24-10-centos ~]# cat -v clean.sh
#!/bin/sh^M
^M
clean() {^M
  for file in $1/*^M
          do^M
                if [ -d $file ]^M
                then^M
                  clean $file^M
                else^M
                  echo $file^M
                  temp=$(tail -100 $file)^M
                  echo "$temp" > $file^M
                fi^M
          done^M
        }^M
^M
dir=logs^M

我们要把^M去掉只需要用vi打开文件,输入

:set fileformat=unix

最后保存再次查看文件,现在正常了

[root@VM-24-10-centos ~]# cat -v clean.sh
#!/bin/sh

clean() {
  for file in $1/*
          do
                if [ -d $file ]
                then
                  clean $file
                else
                  echo $file
                  temp=$(tail -100 $file)
                  echo "$temp" > $file
                fi
          done
        }

dir=logs
clean $dir

最后运行看下效果,可以正常运行了,nice,问题解决了

root@6f240fe0cafa:/code# sh clean.sh
logs/AE/AEcrawl/de91ed5c435f11ec9d070242ac110006.log
logs/AE/AEcrawl/ed48f512435e11ec9d070242ac110006.log
logs/AE/AEcrawl/ede08c92435e11ec9d070242ac110006.log


 

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值