Guide to Unix/Explanations/Pipes and Job Control
Pipes and Redirects[edit | edit source]
We can connect standard input, output, and error of commands to other commands or to files.
The | character is called a pipe and allows for the output of the command which precedes it to be redirected to the command which follows it (instead of being displayed as standard output).
The > character is a "shell redirection feature" and it redirects the output of the command which precedes it to the file whose name follows the said character. If the file already exists, then the > character will cause the file's contents to be wiped out by the new ones being redirected to it. An alternative is to use the >> pair of characters which will append the redirected contents to the file instead of wiping out the file's previous contents.
Job Control[edit | edit source]
You can run multiple commands at once, but only one can be in the foreground. The other commands can be in running at the background or suspended.
Create the shell script "date_loop.sh"
#!/bin/bash while : do date > datefile sleep 10 done
(Note: the shell script can be created with Emacs: run emacs date_loop.sh, type in the above script, then press CONTROL-X CONTROL-S to save the script, then CONTROL-X CONTROL-C to quit Emacs.)
Make date_loop.sh executable:
$ chmod +x date_loop.sh
Run the command in foreground:
Wait a while (about 30 seconds) then use CONTROL-Z to send SIGTSTP signal to the process:
^Z + Stopped (SIGTSTP) date_loop
Look at the last line of datefile:
$ tail -1 datefile; sleep 10; tail -1 datefile Thu Apr 27 10:46:06 BST 2006 Thu Apr 27 10:46:06 BST 2006
Note, that while the process was runnable, it was suspended, thus new "times" were not appended to the file in the 10 second interval between respective tail commands.
Put the process into background:
$ bg  date_loop.sh&
The process is resumed and datefile is being updated again:
$ tail -1 datefile; sleep 10 ; tail -1 datefile Thu Apr 27 10:48:34 BST 2006 Thu Apr 27 10:58:54 BST 2006
Note that you can type commands at the command prompt.
Put the process back into foreground:
$ fg date_loop.sh
Send a 'SIGINT to the process by typing "control-C". This terminates the process. We confirm that datefile is not being updated anymore:
^C $ tail -1 datefile; sleep 20; tail -1 datefile Thu Apr 27 10:59:55 BST 2006 Thu Apr 27 10:59:55 BST 2006