使用 find -exec 执行多个命令,但其中一个命令'cd'



这是我想要实现的目标:

find .. -type d -depth 1 ( -exec cd "{}" ; -exec touch abc ; )

我发现命令的"cd"部分不起作用,我在当前文件夹中而不是在子文件夹中获取文件"abc">

如何在找到的文件夹中执行命令?

澄清一下,按照 Dibery 的评论:我需要能够 cd 到每个文件夹以执行更复杂的命令(触摸就是一个例子(

我在MacOS上,如果它有所作为

命令cd不能与find中的-exec一起使用cd因为它是内置的shell(您可以使用type cd检查(而不是可执行文件(即,没有这样的可执行文件/usr/bin/cd(。在这种情况下,您可以将文件夹名称合并到touch命令中,如下所示:

find .. -type d -depth 1 -exec touch "{}/abc" ;

或者按照您的要求使用git(-C选项允许您像在该目录中一样运行git(:

find .. -type d -depth 1 -exec git -C "{}" some_git_action ;

即使没有find

for i in ../*/; do cd "$i"; some_cmd; cd -; done

cd到该目录并使用cd -返回到原始位置,添加尾随/将使星号仅扩展到目录。

如果 diberys 的评论还不够,您可以将 find 通过管道传输到 while 循环,如下所示:

find . -maxdepth 1 -type d | while read -r dir; do
cd $dir
touch some_file.txt
cd -
done

您可以使用 shell循环并在子 shell 中运行命令,这样您就不必再次更改目录:

for d in ./*/; do (
cd "$d"
touch foo  # Or whatever you want
)
done

或者,要使find命令正常工作,您可以为每个目录启动一个子shell:

find -maxdepth 1 -type d -exec bash -c 'cd "$1"; touch bar' _ {} ;

同样,touch bar可以是任意复杂的东西。

最新更新