今天群里有人问了这么一个问题:
[root@iZ28mh9xca0Z script]# find ./ -type f-name "*.txt" -exec echo "123" > {} \;
[root@iZ28mh9xca0Z script]# cat a.txt 1.txt
[root@iZ28mh9xca0Z script]#
发现123并没有写到find找到的.txt文件里(确定可以找到.txt文件,并有w权限)
自己尝试了几次,也是这样的问题, 问了隔壁的大神,给了我这个命令:
[root@iZ28mh9xca0Z script]# find ./ -type f -name "*.txt" -exec bash -c 'echo 123 > "{}" ' \;
[root@iZ28mh9xca0Z script]# cat a.txt 1.txt
123
123
[root@iZ28mh9xca0Z script]#
发现可以,那么问题来了,为什么可以呢?
查询资料和请教大神,我自己这样理解:
参考资料:http://superuser.com/questions/410321/subshell-arguments-in-exec-parameter-for-find1
当我们使用了find命令时其实是进入了一个子shell里面,而使用-exec时会跳出这个子shell,回到当前shell,当然后面echo的{}对象不是find找到的txt文件,这时我们就要使用bash -c回到子shell里面来,这样后面的echo的{}对象才有txt文件。通过man bash我们可以看到:
-c string If the -c option is present, then commands are read from string.
If there are arguments after the string, they are assigned to the
positional parameters, starting with $0.
解释来说就是bash -c会调用后面引号里面的字符串,如果这个字符串是命令,就会执行这个命令。而如果参数在字符串之后,则需要用$0来调用后面的参数。
自己的理解,各位看看是否正确。
编辑回复