1

I have a bash for loop like this:

for file in *.mp4; do
  command1 "${file}" && command2 "${file}"
done

This makes command2 to run whenever command1 is successful, which is expected.

Now what I want is for the loop to wait only for command1 to finish , but no need to wait for command2 to finish before iterating. Is there a way to do this?

What I've tried, but did not work:

  • command1 && command2 & - does not wait for command1 to exit, runs parallel
  • command1 && ( command2 & ) - waits for command2 to exit, no need
1

2 Answers 2

6

A bit more verbose, but this should work:

for file in *.mp4; do
  if command1 "${file}"; then
    command2 "${file}" &
  fi
done
0
0

I like the answer of @muru and accepted it as the main answer.

Also found a similar way and I'm posting it here as an alternative:

for file in *.mp4; do
  command1 "${file}"
  [ "${?}" -eq 0 ] && command2 "${file}" &
done
1
  • What benefit do you see in spawning an extra process to evaluate the result that the if above gave you at no cost?
    – tink
    Nov 29, 2023 at 3:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .