1

Trying to pull an entry from two files (foofile, barfile) and pass them into a third file (dothis.sh) as arguments. It works for bar but not for foo since this looks be a scope related issue. I tried to nest the foo loop into the bar loop too with no success:

    #!/bin/bash
    while read foo
                do
                        #echo $foo
                        export foo
    done < FooFile

    while read bar
        do
                #echo $bar
                export bar
    ./dothis.sh $bar $foo
    done < BarFile
3
  • 2
    paste FooFile BarFile | xargs -n 2 ./dothis.sh??? Commented Mar 26, 2019 at 20:47
  • Do you want to dothis.sh for each possible combination of foo and bar or only combine them for the same line number? When you want each combination, move done < FooFile towards the end of the script (after the other done) Commented Mar 26, 2019 at 23:14
  • Using the paste command did help. Thank you everyone for the help. Commented Apr 3, 2019 at 15:26

2 Answers 2

2

Here's a way to loop with two inputs at the same time in bash:

#!/bin/bash

while read -u 100 foo && read -u 101 bar; do
    ./dothis.sh "$foo" "$bar"
done 100<FooFile 101<BarFile

It will terminate when one file has no more lines to read.

Sign up to request clarification or add additional context in comments.

1 Comment

If you want it to run until both files have been fully read, just use || instead of && between the two read commands.
1

foo is in scope in your program, but it is empty.
Consider this code:

foo="test"
while read foo; do echo $foo; done < /dev/null
echo "foo=$foo"

The result is:

foo=

The problem is that foo will be set to empty when read has no input. That's what's happening in your program.

That said, pay attention to oguzismail's comment. (S)he is leading you a good direction:

paste FooFile BarFile | xargs -n 2 ./dothis.sh

It's really an excellent start and probably all you'll need in the simple cases where FooFile and BarFile have the same amount of entries.

1 Comment

And this may be because the files don't have the same number of lines. Easily tested with, for example: wc -l FooFile BarFile

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.