我正在编写一个脚本,需要在特定文件夹的每个子目录中执行一个操作。
最有效的写法是什么?
我正在编写一个脚本,需要在特定文件夹的每个子目录中执行一个操作。
最有效的写法是什么?
当前回答
这将创建一个子shell(这意味着当while循环退出时,变量值将丢失):
find . -type d | while read -r dir
do
something
done
这不会:
while read -r dir
do
something
done < <(find . -type d)
如果目录名中有空格,这两种方法都可以工作。
其他回答
for D in `find . -type d`
do
//Do whatever you need with D
done
找到。-type d -print0 | xargs -0 -n 1 my_command
最简单的非递归方法是:
for d in */; do
echo "$d"
done
末尾的/表示只使用目录。
没有必要
找到 呜 ...
这将创建一个子shell(这意味着当while循环退出时,变量值将丢失):
find . -type d | while read -r dir
do
something
done
这不会:
while read -r dir
do
something
done < <(find . -type d)
如果目录名中有空格,这两种方法都可以工作。
你可以试试:
#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/
for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
cd "$f"
<your job here>
done
或类似的…
解释:
找到。-maxdepth 1 -mindepth 1 type d: 只查找最大递归深度为1(仅为$1的子目录)和最小递归深度为1(不包括当前文件夹)的目录。