Most people who are familiar with Linux, realize that there are ways of chaining processes to run one after another. Typically this is done by writing a script, or using && to daisy chain additional commands on command line.
There is, however, another way to do this; if you’ve already issued a command and want to add another command after the original has already started. This is especially useful if you’re unzipping, say a 15 gigabyte database dump, and you want to make sure that the import happens immediately after the import is complete.
Here’s an example of what would happen if I were entering the commands manually.
Macintosh:~ chriscase$ scp user@hostname.com:archive/database.sql.gz .
Macintosh:~ chriscase$ gunzip database.sql.gz
Macintosh:~ chriscase$ mysql -u dbusername -pdbpassword dbname < database.sql
Since I’m not going to stay glued to the console for the entire duration of this process, I either need to write a script or figure out another technique, so I keep things moving along.
As it turns out, there is a very simple way to accomplish this, with the command wait. This command has the ability to wait until a specified process is complete before executing a command.
Here’s an example of how this could be used, if you wanted to add the last two processes after the scp from the above example had already begun.
Macintosh:~ chriscase$ scp user@hostname.com:archive/database.sql.gz .
Once the download is kicked off, you can kick it into the background by using [ctrl-z] which will pause the process and then issuing the command [bg]. This will put the paused process running into the background. Now, to chain the other processes afterward, you can do the following.
Macintosh:~ chriscase$ wait %1 && gunzip database.sql.gz && mysql -u dbusername -pdbpassword dbname < database.sql
The above code will wait to execute until the scp is done, then it will use gzip to unzip the file and mysql to import the database dump file. Now that you've done this, you can go off and do something else, confident that your database will be done importing in a few hours.