drei34
drei34

Reputation: 11

running basic commands all at once and then sequentially after they all finish

How would I run several commands as below so that the last line executes (cleans up) after all the background ones are done?

echo "oyoy 1" > file1 &
echo "yoyoyo 2" > file2 &
rm -f file1 file2

Of course the echo commands are different for me and take a long time to finish (I can delete the files manually or with another script I know, but I was wondering how to have this done in one script..)

Thanks!

Upvotes: 1

Views: 162

Answers (2)

SuperTetelman
SuperTetelman

Reputation: 617

Alternatively if you have a bunch of things you are running and you only need to wait for a few processes to complete you can store a list of pids and then only wait for those.

echo "This is going to take forever" > file1 &
mypids=$!
echo "I don't care when this finishes" > tmpfile &
echo "This is going to take forever also" >file2 &
mypids="$mypids $!"
wait $mypids

Upvotes: 0

user000001
user000001

Reputation: 33387

From the docs

 wait [n ...]
      Wait  for each specified process and return its termination sta-
      tus.  Each n may be a process ID or a job  specification;  if  a
      job  spec  is  given,  all  processes in that job's pipeline are
      waited for.  If n is not given, all currently active child  pro-
      cesses  are  waited  for,  and  the return status is zero.  If n
      specifies a non-existent process or job, the  return  status  is
      127.   Otherwise,  the  return  status is the exit status of the
      last process or job waited for.

So you can wait for the baackground processes to finish like this:

echo "oyoy 1" > file1 &
echo "yoyoyo 2" > file2 &
wait
rm -f file1 file2

Upvotes: 2

Related Questions