编辑一个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