如果文件夹为空则重命名文件夹的脚本

如果文件夹为空则重命名文件夹的脚本

这对我不起作用。

#!/bin/bash
# script to find empty folder in current folder and rename it.

#find empty folder and write it into fef.txt
find . -type d -empty -maxdepth 1 -mindepth 1 | cut -c2- > fef.txt;

#number line of fef.txt
nl_fef=$(cat fef.txt | wc -l);

#rename loop
for i in {1..$nl_fef};
do

# folder path
f=$(pwd);
d=$(cat fef.txt | head -$i | tail -1)
folder_path=$f$d

#rename folder_name to folder_name.empty 
mv "$folder_path" "$folder_path".empty;

done;

这是输出:

find: warning: you have specified the -maxdepth option after a non-option argument -type, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it).  Please specify options before other arguments.

find: warning: you have specified the -mindepth option after a non-option argument -type, but options are not positional (-mindepth affects tests specified before it as well as those specified after it).  Please specify options before other arguments.

head: invalid option -- '{'
Try 'head --help' for more information.

答案1

它不起作用,因为括号扩展不接受变量

除此之外,你的脚本中还有很多奇怪或“糟糕”的东西,例如:

  • 为了获得更好的性能,将-maxdepth 1-mindepth 1作为的第一个参数find
  • 为什么要截断.并添加$pwd而不是只保留相对路径?
  • 使用 wc -l < fef.txt而不是这种无用的用法cat
  • 使用sed获取线路

但为什么你不简单地使用find -exec

find . -maxdepth 1 -mindepth 1 -type d -not -name  -empty -exec mv {} {}.empty \;

如果不再为空则恢复:

find . -maxdepth 1 -mindepth 1 -type d -name "*.empty" -not -empty -exec rename 's/.empty$//' {} +

或组合:

find . -maxdepth 1 -mindepth 1 -type d \
  \( -empty -not -name "*.empty" -exec rename 's/$/.empty/' {} + \) \
  -or \( -not -empty -name "*.empty" -exec rename 's/.empty$//' {} + \)

如果为空则会重命名.empty,如果不为空则会删除.empty

相关内容