Ash*_*ish 23 bash shell-script
我希望我的 shell 脚本访问主目录中的所有子目录。在目录中做一些事情,将输出发送到假脱机文件并移动到下一个目录。考虑 Main Dir = /tmp Sub Dir = ABCD(四个子目录)
cha*_*aos 33
使用for
循环:
for d in $(find /path/to/dir -maxdepth 1 -type d)
do
#Do something, the directory is accessible with $d:
echo $d
done >output_file
Run Code Online (Sandbox Code Playgroud)
它只搜索目录的子目录/path/to/dir
。请注意,如果目录名称包含空格或特殊字符,则上面的简单示例将失败。更安全的方法是:
find /tmp -maxdepth 1 -type d -print0 |
while IFS= read -rd '' dir; do echo "$dir"; done
Run Code Online (Sandbox Code Playgroud)
或者简单地说bash
:
for d in $(find /path/to/dir -maxdepth 1 -type d)
do
#Do something, the directory is accessible with $d:
echo $d
done >output_file
Run Code Online (Sandbox Code Playgroud)
(请注意,与此相反find
,还考虑到目录的符号链接并排除隐藏的)
我得到了解决方案。下面的 find 命令满足我的要求。
find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && ls -l |awk '{ print $9 }' |grep `date +"%m%d%Y"`|xargs echo" \;
Run Code Online (Sandbox Code Playgroud)