0

On my first run I need curl to run and wait for response. DB has a trigger that updates a field and I need to wait for that. Then on all my other curls to run on separate threads. I cannot use the parallel options for curl as the version we have does not have it and I cannot update it anyway so I have to go old school and do

for ...
  curl "some curl options" &
end for loop

wait # this waits for all the threads to finish

So I need the "&" sign to be set after the first run. FYI my curl command is 20 lines long and I did try this at the end of the curl command but it doesn't work. Trying single and double quotes around the & sign doesn't work either and give me "unexpected end of file" error.

$(if [[ $firstRun == false ]]; then echo & fi)
2
  • Why don't you just do the first one outside the loop? Commented Oct 30, 2023 at 17:14
  • The curl command is huge and has many conditionals in it. It would be ugly code and just bad coding practice. Commented Oct 30, 2023 at 19:24

3 Answers 3

1

You could write a wrapper function to conditionally run its arguments as a command in the background:

conditionalbg() {
    if [ "$1" = true ]; then
        shift
        # run the passed command in the foreground
        "$@" &
    else
        shift
        # run the passed command in the foreground
        "$@"
    fi
}

...
runinbg=false
for ...
    conditionalbg "$runinbg" curl "some curl options"
    runinbg=true
end for loop
Sign up to request clarification or add additional context in comments.

1 Comment

This appears to be the best solution for my situation! Logic is reversed but easily fixed. When true then don't daemon it. For all others then add the &. Thank you for the speedy response!
0

You can't add syntax to command lines dynamically. So just write two identical commands, one without &.

firstRun=true
for ...; do
    if [[ $firstRun = true ]]
    then 
        curl "some curl options" 
        firstRun=false
    else
        curl "some curl options" &
    fi
done
wait

If you don't want to repeat the whole curl command, put it in a function.

Comments

0

Put your curl command in a function then call the function with or without & as appropriate:

doCurl() {
    curl "some curl options"
}

doCurl
for ...
  doCurl &
end for loop

wait # this waits for all the threads to finish

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.