0

So you all know this right? Looping through the content of a file in Bash

So what I want to do is loop the contents of a file to arguments. Which change outputs etc

What I tried:

while read $1 & $2 & $3; do
#also tried:
#while read $1 $2 $3; do
    echo ${1}
    echo ${2}
    echo ${3}

    ./${1}.sh & ./${2}.sh & ./${3}.sh

done <file.txt

Results in:

#arguments aren't echoed
./script.sh: line 31: ./.sh: No such file or directory
./script.sh: line 31: ./.sh: No such file or directory
./script.sh: line 31: ./.sh: No such file or directory
#scripts aren't executed

file.txt contents

apple_fruit
#$1
apple_veggie
#$2
veggie_fruit
#$3
pear_fruit
#$1
pear_veggie
#$2
veggie_fruit
#$3

This loops like this, in this pattern ^^

I've also tried changing the file to this:

apple_fruit apple_veggie veggie_fruit
pear_fruit pear_veggie veggie_fruit

In a nutshell:

I want $1 to be replaced by apple_fruit, $2 to be replaced by apple_veggie, and $3 to be replaced by veggie_fruit. Then when it hits done I want it to replace $1 with pear_fruit, $2 with pear_veggie, and so on.

Related Mini-Questions

And also, to get this to work, do you add no argument when you're entering this script

script.sh

or do you actually have to put something in, if you do what? Because the argument is always going to be changing.

script.sh mystery mystery mystery

2 Answers2

0

You could use bash readarray builtin to read lines into an array (line):

readarray line < file.txt
echo ${line[@]}

output:

apple_fruit                                                              
apple_veggie                                                             
veggie_fruit                                                             
pear_fruit                                                               
pear_veggie                                                              
veggie_fruit

Then you could do

printf './%s.sh & '  "${line[@]}" | sed 's/ \& $//'         

which outputs

./apple_fruit.sh & ./apple_veggie.sh & ./veggie_fruit.sh & ./pear_fruit.sh & ./pear_veggie.sh & ./veggie_fruit.sh
builder-7000
  • 7,131
  • 3
  • 19
  • 43
0

Three lines, three reads:

while IFS= read -r l1
      IFS= read -r l2
      IFS= read -r l3
do
    echo "$l1, $l2, and $l3"
done <<EOF
apple_fruit
apple_veggie
veggie_fruit
pear_fruit
pear_veggie
veggie_fruit
EOF

The output is

apple_fruit, apple_veggie, and veggie_fruit
pear_fruit, pear_veggie, and veggie_fruit

There's no real reason to involve the positional parameters here; just use regular variables.

chepner
  • 497,756
  • 71
  • 530
  • 681