3

I have need to execute a command in a script an arbitrary number of times with associated arbitrary parameters.

I've decided the script will take its cue from a parameter file (parameter.txt) where lines are of the form:

label param1 param2

For each line in parameter.txt, I'll call the command with the specified parameters.

So far, my tinkering is moving along the lines of the following, but it's looking messy:

while read line; do 
    echo $line | sed -r 's/[^ ]+ ([^ ]+).+/\1/' && 
        echo $line | sed -r 's/[^ ]+ [^ ]+ ([^ ]+)/\1/'
done < parameter.txt

My command is of the form:

mycmd -a param1 -b param2 > label

Could I get some suggestions how I might simplify this?

I'm doing this for a small embedded system whose 'helper' commands are in short supply (xargs for example isn't available, and things like awk are hobbled busybox implementations), and I'm using version 2 (2.04g I think) of BASH.

3 Answers 3

6
while read label param1 param2; do
    mycmd -a "$param1" -b "$param2" > "$label"
done < parameter.txt
Sign up to request clarification or add additional context in comments.

2 Comments

Love it. Full points for brevity and making me feel sheepish for not RFM'ing the read man page.
If you want to ignore after param3, use read label param1 param2 ignored instead.
3

I'd suggest a function, as long as there aren't any embedded spaces.

function x()
{
    mycmd -a $2 -b $3 >$1
}

while read line; do x $line ; done <parameter.txt

1 Comment

Nice. I hadn't thought of parameterizing the line with a function call, will add that to my bag of tricks. +1
1

Try this:

while read line ; do
    set -- $line
    dest="$1"
    shift

    mycmd "$@" > "$dest"
done < parameter.txt

should work. If the parameters in the file have spaces, you will have to quote them properly.

I suggest to add the -a, -b to the file parameter.txt because generating them on the fly is probably brittle.

If you don't like this solution, then I suggest to create a new script from this one which contains the actual commands. That way, you can easily debug any problems.

When the script looks okay, you can source it with source ./generated.sh (yes, you have to specify the path).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.