将文件移动到同一目录中具有旧扩展名的文件

时间:2014-10-29 21:39:17

标签: linux bash shell

在我获得作业的错误后,我有一个问题,因为它似乎适用于我自己的测试。我将发布脚本和下面的错误。 Bash脚本

#!/bin/bash
for file in $1
do $file | grep \.old$ > /dev/null
 if [ "$file" != 0 ]
then mv $file $file.old
else $file
fi
done

Files created in 'testdir:

file1  file2.old  file3old  file4.old

Execution of 'oldfiles testdir':


'oldfiles testdir' incorrectly produced some output or errors:
for file in $1
  do $file | grep \.old$ > /dev/null
  if [ "$file" != 0 ]
    then mv $file $file.old
  else $file
  fi
done
+ for file in '$1'
+ grep '.old$'
+ /var/tmp/uli101.npkrause.assign4.8938.testdir
/home/npkrause/scripts/oldfiles: line 4: /var/tmp/uli101.npkrause.assign4.8938.testdir: Is a directory
+ '[' /var/tmp/uli101.npkrause.assign4.8938.testdir '!=' 0 ']'
+ mv /var/tmp/uli101.npkrause.assign4.8938.testdir /var/tmp/uli101.npkrause.assign4.8938.testdir.old

Files in 'testdir' after 'oldfiles' was run:
ls: cannot access /var/tmp/uli101.npkrause.assign4.8938.testdir: No such file or directory

Filenames don't seem to be correct

Please hit <Enter> to continue with the Assignment

1 个答案:

答案 0 :(得分:0)

dir=$1
for file in "$dir"/* ; do
    [[ $file == *.old ]] || mv -- "$file" "$file.old"
done

引用$ dir和$ file的所有用法(双方括号内除外)以防止名称中的空格或元字符。

使用&#39; mv - &#39;防止目录名称以&#39; - &#39;。

开头