Andrew
Andrew

Reputation: 1529

In a bash script, how do I provide values contained in a text file to the switch of a program execution?

I would like to write a bash script in Linux that executes a program multiple times (e.g., 3 times) and that specifies a switch value based on a list of values provided in a text file.

For example, suppose that there is some program programname that has a switch -switch that takes a floating point number as input. So, one execution of the program might read:

programname -switch 0.05

where 0.05 is a particular value passed to the switch -switch.

Now I would like to read in some sort of text file that has a list of values that I would like to pass, in succession, to -switch in separate calls of programname. My text file test.txt might contain these data:

0.05
3.19
100.75

I would like to write a bash script that will read in the text file and effectively make these calls in succession:

programname -switch 0.05
programname -switch 3.19
programname -switch 100.75

I am thinking of something like this:

#!/bin/bash
for i in {1..3}
do
programname -switch $x
done

But, what should I type in place of $x? In other words, I am not sure how to read in test.txt and provide its contents, one-by-one, to -switch as the for loop runs. Do you have any advice? Thank you!

Upvotes: 3

Views: 711

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360153

There is no need to use any external utilities. The counter increment and read can be done together as shown or the counter increment can be moved anywhere within the loop.

while ((i++)); read -r value
do
    programname -switch "$value" -other "$i"
done < test.txt

Upvotes: 4

trojanfoe
trojanfoe

Reputation: 122391

values.txt:

0.05
3.19
100.75

script.sh:

#!/bin/bash

counter=1
for value in $(cat values.txt)
do
    programname -switch $value -counter $counter
    counter=$(expr $counter + 1)
done

Upvotes: 1

Related Questions