当我rm *.old.*
在命令行上执行该操作时,它会正确删除,但是当我在脚本的以下部分中执行此操作时,它不会保留所有*.old.*
文件。
我的bash脚本出了什么问题:
for i in ./*; do
if [[ -f $i ]]; then
if [[ $i == *.old.* ]]; then
oldfile=$i
echo "this file is to be removed: $oldfile"
rm $oldfile
exec 2>errorfile
if [ -s $errorfile ]
then
echo "rm failed"
else
echo "removed $oldfile!"
fi
else
echo "file with old extension does not exist"
fi
orig=$i
dest=$i.old
cp $orig $dest
echo "Copied $i"
else
echo "${i} is not a file"
fi
done
如果我了解您的工作(删除带.old
后缀的任何文件,并复制带.old
后缀的任何现有文件的副本),则可以使用find代替:
#!/bin/sh
find . -maxdepth 1 -name \*.old -type f -printf "deleting %P\n" -delete
find . -maxdepth 1 -type f -printf "copying %P to %P.old\n" -exec cp '{}' '{}.old' \;
-maxdepth 0
停止在子目录中查找命令,-type f
仅查找常规文件;-printf
创建消息(%P
是找到的文件名)。在-exec cp
调用复印功能和'{}'
为文件名
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句