2

I'm trying to us bash scripting to batch execute an existing package. The input for each execution requires two input files. I can either use regular names or place each pair in its own sub-directory to make sure each pair stays together. I've got bits and pieces but nothing that loops over TWO files or enters a sub-directory, does something, moves up and repeats on the next sub-directory.

This will perform what I want on a single directory containing the pair of files (each file pair is named e.g. ABC10f.txt and ABC10r.txt):

#!/bin/bash
#
f=$(ls *f.txt)
  echo "forward -> $f"
i=$(ls *r.txt)
  echo "reverse -> $i";
/path/to/package [options] $f $i;

The following will loop through each sub-directory in my main directory but only executes what I only when it gets to the last one (Note: I was testing it with helloworld.sh – I thought if I could get it to list each sub-dir and echo "hello world" after each I'd be on my way to doing what I want; instead I get a list of all sub-directories followed by a single "hello world"):

#!/bin/bash
#
myCommand=/path/to/scripts/helloworld.sh

for d in ./; do
  find * -maxdepth 1 -type d 
    cd $d
    echo $PWD
    exec "$myCommand"
done

A little help putting this together?

Eugeniu Rosca
  • 5,177
  • 16
  • 45
  • 2
    Don't try to get both lists. Get one list and transform the name into the paired name. – Etan Reisner Jul 10 '15 at 17:55
  • `but only executes what I only when it gets to the last one` => The first `cd $d` in your second script is *valid*, but the subsequent are NOT. Either `cd` using an absolute path or `cd` to a relative path in a subshell. – Eugeniu Rosca Jul 10 '15 at 18:22

1 Answers1

2

Make your helloworld.sh look like:

#!/bin/bash

for f in *f.txt; do
    r="${f/f.txt/r.txt}"
    echo "  f: $f"
    echo "  r: $r"
    /path/to/package [options] "$f" "$r";
done

And your second sript:

#!/bin/bash
# '*/' pattern matches all of the subdirectories in the current directory
for d in */; do
    # doing any actions in a subshell ()
    (cd "$d" && echo "$(pwd)" && bash /path/to/scripts/helloworld.sh)
done
Eugeniu Rosca
  • 5,177
  • 16
  • 45
  • Yes! This seems like exactly the right approach. Thank you so much. – user5103671 Jul 10 '15 at 19:26
  • If anyone is wondering what the `r="${f/f.txt/r.txt}"` line does, it's replacing "f.txt" with "r.txt" in the string contained in the "f" variable. See this for more info on this syntax: http://wiki.bash-hackers.org/syntax/pe#search_and_replace – user31389 Feb 22 '18 at 17:14