Iterate shell script over list of subdirectories

天涯浪子 提交于 2019-12-13 09:40:27

问题


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.

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

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?


回答1:


    for dir in ./* ./**/*    # list directories in the current directory
    do
        python $dir
    done

./* are files in dir and ./**/* are files in subfolders.

Make sure you have only python files in your directory it will run all the files in that directory



来源:https://stackoverflow.com/questions/54909302/iterate-shell-script-over-list-of-subdirectories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!