0

I'm currently trying to write a script which will cd to a directory and execute a python script if it matches a predefined string to the directory name. I need the code to change to a directory with the string 'batch' in it and execute the script. The most useful tool would probably be the case statement, but I can't get it to work for some reason. I'm fairly new to bash scripting, so i'm not really sure why this isn't working.

Here's my code:

#!/bin/bash
dir_string="batch"
workingdir=$PWD

for dir in *;do
echo "$dir"

if [[-d "$dir"]]; then

case "$dir_string" in
   $dir)

        cd $workingdir/$dir

        for i in *;do
        execute python script
        done
        ;;

      *)
        echo "Can't find appropriate directories."
       ;;
esac
fi
done

Any help is appreciated!

1 Answers1

0

What you are trying to achieve with your script, can be achieve with find:

#!/bin/bash
dir_string="batch"
workingdir=$PWD
for dir in $(find "$workingdir" -type d|grep $dir_string)
    do
        (cd "$dir" && execute python script)
    done 
Ardit
  • 1,522
  • 17
  • 23
  • 2
    Why not just use find $workingdir -name "*$batch*" -type d -execdir python '{}' \; without the loop then? – Raman Sailopal Oct 04 '17 at 13:43
  • That's even better :) – Ardit Oct 04 '17 at 14:08
  • 1
    `find $workingdir` is quite buggy. What if your directory name contains spaces? Always quote expansions. – Charles Duffy Oct 04 '17 at 14:22
  • 1
    Also, `(cd $dir)` does nothing after the subshell it's run in exits. It most definitely doesn't change the directory your Python script is executed in. (cd "$dir" && exec python scriptname)` is both more efficient (creates exactly one subshell and consumes it by `exec`ing the script) and more correct (handles directory names with spaces, actually makes the `cd` apply to the Python interpreter). – Charles Duffy Oct 04 '17 at 14:23
  • 1
    @Ardit, ...which is to say, this answer needs to be [edit]ed before it's at a reasonable standard of correctness. – Charles Duffy Oct 04 '17 at 14:24