c 网站开发案例代码,网站建设培训总结,柳州市建设中心网站首页,wordpress 找回密码最近有这样一个需求#xff0c;删掉某目录下的一些文件夹。其实就是名为“CVS”的文件夹#xff0c;用过CVS的人都知道#xff0c;CVS会在目录的每一级建立一个名为CVS的文件夹#xff0c;里面放着CVS相关信息#xff0c;我需要将某目录下所有的名为“CVS”的文件夹删掉。… 最近有这样一个需求删掉某目录下的一些文件夹。其实就是名为“CVS”的文件夹用过CVS的人都知道CVS会在目录的每一级建立一个名为CVS的文件夹里面放着CVS相关信息我需要将某目录下所有的名为“CVS”的文件夹删掉。在Linux下其实很简单使用find命令 [plain] view plaincopy find . -name CVS -exec rm -rf {} \; 看似没问题但却报错了 [plain] view plaincopy find: ./CVS: No such file or directory 检查了下发现其实./CVS这个文件夹确实存在而且此时已经被删掉了算是功德圆满但是为什么还报错 没办法记得find完成这种功能还有一种写法 [plain] view plaincopy find . -name CVS -exec rm -rf {} \ 抱着试试的态度令人意外的是这种方式成功执行并未报任何错误这就叫人疑惑了没办法只好求助于男人man -exec command ;Execute command; true if 0 status is returned. All followingarguments to find are taken to be arguments to the command untilan argument consisting of ; is encountered. The string {}is replaced by the current file name being processed everywhereit occurs in the arguments to the command, not just in argumentswhere it is alone, as in some versions of find. Both of theseconstructions might need to be escaped (with a \) or quoted toprotect them from expansion by the shell. See the EXAMPLES sec-tion for examples of the use of the -exec option.
The speci- fied command is run once for each matched file.The command isexecuted in the starting directory. There are unavoidablesecurity problems surrounding use of the -exec option; youshould use the -execdir option instead. 另外一种 -exec command {} This variant of the -exec option runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invoca- tions of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of {} is allowed within the command. The command is executed in the starting directory. 看了半天我注意到他们的区别红字体标注。 也就是说 -exec ; 为每一个匹配的文件都执行了一次命令具体到此处就是 rm -rf 命令而 “-exec” 只是把匹配的文件名作为命令的参数append到命令后面即是这样 rm -rf file1 file2 file3 可是这种差别为什么会导致如此明显的差异呢 想了想, 悟到了 #1的执行过程应该是这样 1. 记录并遍历当面层的所有目录和文件并对比是否匹配。 2. 匹配了名为CVS的文件夹然后执行了命令 rm -rf ./CVS, 3. 根据之前的记录多所有目录进行递归遍历此时问题出现当程序试图进入该层名为“CVS”的目录进行遍历是发现此目录不存在所以报错。为什么这个目录没了哈在第二步已经被删掉了 是这样吗: 可以验证 [plain] view plaincopy find . -maxdepth 1 -name CVS -exec rm -rf {} \; -maxdepth 参数指明匹配只发生在当前目录并不深入子目录 结果是这个命令没有报错也验证了之前的猜想。 在此记录以备后查。