在子目录列表上迭代Shell脚本 [英] Iterate shell script over list of subdirectories
问题描述
我有一个文件夹(我们叫它folder1
仅包含子目录.我想编写一个shell脚本,该脚本在每个子目录上迭代几个python脚本.照原样,我必须输入每个子目录的绝对路径在脚本中,但是我希望能够从cd
到folder1
并从那里简单地运行shell脚本,并使其在子目录上自动进行迭代,无论它们的名称或folder1
的位置如何.
I have a folder (let's call it folder1
that contains only subdirectories. I want to write a shell script that iterates several python scripts over each subdirectory. As it is, I have to type out the absolute path to each subdirectory within the script, but I want to be able to cd
to folder1
and simply run the shell script from there and have it automatically iterate over the subdirectories, whatever their name or the location of folder1
.
当前代码(保存为shellscript.sh):
Current code (saved as shellscript.sh):
#! /bin/sh
declare -a arr=("/path/folder1/subdir1" "/path/folder1/subdir2" "/path/folder1/subdir3" "/path/folder1/subdir4")
for i in "${arr[@]}"
do
echo "$i"
python /path/to/pythonscript1.py "$i"
python /path/to/pythonscript2.py "$i"
done
然后我可以通过打开终端(Mac OSX v 10.13.6)并运行sh path/to/shellscript.sh
来运行它.我希望脚本中的arr
声明能够根据我所在的任何cwd的内容自动填充.我发现
Then I can run it by opening up a Terminal (Mac OSX v 10.13.6) and run sh path/to/shellscript.sh
. I want the arr
declaration early in the script to automatically populate based on the contents of whatever cwd I'm in. I found this useful link and was able to run that as a standalone command in the Terminal but can't figure out how to incorporate it into the shell script. Any tips?
推荐答案
for dir in ./* ./**/* # list directories in the current directory
do
python $dir
done
./*是dir中的文件,./**/*是子文件夹中的文件.
./* are files in dir and ./**/* are files in subfolders.
确保目录中只有python文件,它将运行该目录中的所有文件
Make sure you have only python files in your directory it will run all the files in that directory
这篇关于在子目录列表上迭代Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!