5. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Use streams, pipes and redirects
Input and output redirection
5
Redirect with pipes (|) are processed 1st
, other redirect (> and <) are processed left to right.
Redirection Effect of redirection
command1 | command2 Output from command1 is input for command2
command < file Command reads input from a file
command > file Output of command goes to file
command 2> file Errors from the command go to a file
command >> file Output of a command is added to a file
command > file 2>&1 Output and errors go to a file
command >& file
command &> file
$ ls > file
$ cat < file
$ ls -la | grep file
$ cat /etc/passwd | sed 's/:.*//'
$ badcommandorfilename 2> errorlog
$ grep pop3 /etc/* 2>/dev/null
$ grep pop3 /etc/* 2>&1 | less
$ less < errorlog
$ less errorlog
Ex:
11. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Standard output redirection (>, >>)
[jack@foo jack]$ uptime
5:09pm up 8:26, 6 users, load average: 0.22, 0.20, 0.20
Ex:
Standard output is the terminal, by default. The following redirections are possible:
11
Use streams, pipes and redirects
No redirection
Redirection to a file (“>” means “to”). If the file already exists, it is overwritten.
[jack@foo jack]$ uptime > Uptime-file
[jack@foo jack]$ ls -l Uptime-file
-rw-rw-r-- 1 jack jack 62 Apr 8 17:09 Uptime-file
[jack@foo jack]$ cat Uptime-file
5:09pm up 8:26, 6 users, load average: 0.13, 0.18, 0.19
Ex:
Redirection appending to a file (“>>” means “to the end of”)Ex:
[jack@foo jack]$ uptime >> Uptime-file
[jack@foo jack]$ cat Uptime-file
5:09pm up 8:26, 6 users, load average: 0.13, 0.18, 0.19
5:10pm up 8:27, 6 users, load average: 0.24, 0.21, 0.20
Redirecting to a program. Here the output of uptime is being piped as the input to wc.Ex:
jack@foo jack]$ uptime | wc
1 10 62
12. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Standard error redirection (2>, 2>>, 2>&1)
By default, Linux processes produce two error streams.
Regular output is sent to stdout (standard output “1”) and errors are sent to stderr (standard error “2”).
12
Use streams, pipes and redirects
Ex: [jack@foo jack]$ tar cf sysconfig.tar /etc/sysconfig
tar: Removing leading `/' from member names
tar: /etc/sysconfig/rhn/systemid: Cannot open: Permission denied
tar: /etc/sysconfig/rhn/up2date-keyring.gpg: Cannot open: Permission
denied
tar: /etc/sysconfig/iptables: Cannot open: Permission denied
tar: /etc/sysconfig/static-routes: Cannot open: Permission denied
tar: Error exit delayed from previous errors
Output sent to stderr:
•Error messages (command 2>/dev/null)
•Warning messages (command 2>> warning.log)
•Debugging and progress indicators (command 2>&1 | less )
If stderr is not redirected, error output is displayed on the terminal.
13. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Standard error redirection (2>, 2>>, 2>&1)
(command 2>/dev/null) sending the errors to a file. It is quite common to send error text to /dev/null
13
Use streams, pipes and redirects
Ex:
[jack@foo jack]$ tar cf sysconfig.tar /etc/sysconfig 2> /dev/null
[jack@foo jack]$ tar cf sysconfig.tar /etc/sysconfig 2> warning.log
append the errors to an existing file ...Ex:
[jack@foo jack]$ tar cf pam.tar /etc/pam.d/
tar: Removing leading `/' from member names
tar: /etc/pam.d/sshd: Cannot open: Permission denied
tar: Error exit delayed from previous errors
[jack@foo jack]$ tar cf pam.tar /etc/pam.d/ 2>>warning.log
[jack@foo jack]$ cat warning.log
tar: Removing leading `/' from member names
tar: /etc/sysconfig/rhn/systemid: Cannot open: Permission denied
tar: /etc/sysconfig/rhn/up2date-keyring.gpg: Cannot open: Permission denied
tar: /etc/sysconfig/iptables: Cannot open: Permission denied
tar: /etc/sysconfig/static-routes: Cannot open: Permission denied
tar: Error exit delayed from previous errors
tar: Removing leading `/' from member names
tar: /etc/pam.d/sshd: Cannot open: Permission denied
tar: Error exit delayed from previous errors
14. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Standard error redirection (2>, 2>>, 2>&1)
The notation 2>&1 means “stderr(2) to copy of stdout(1)”.
The following all send standard error output to the same destination as standard output:
• command >file 2>&1
• command 2>file 1>&2
• command &> file
• command >& file (this is not the preferred method)
• command 2>&1 | anothercommand
14
Use streams, pipes and redirects
discard the output and the errors from the commands, sending them to /dev/null.Ex:
[jack@foo jack]$ tar vcf pam.tar /etc/sysconfig >/dev/null 2>&1
[jack@foo jack]$ nosuchcommandorfilename 2>/dev/null 1>&2
[jack@foo jack]$ ls -la /root 2>/dev/null 1>&2
[jack@foo jack]$ updatedb >& /dev/null &
[jack@foo jack]$ killall -HUP inetd sendmail &> /dev/null
[jack@foo jack]$ killall -HUP inetd sendmail &> /dev/null
commands send standard error output to the same destination standard output (a program).Ex:
[jack@foo jack]$ bash -x /etc/init.d/network restart 2>&1 | less
[jack@foo jack]$ tar -c / 2>&1 | less
[jack@foo jack]$ strace mailq 2>&1 | less
18. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Standard input redirection (<, <<EOF, |)
[jack@foo jack]$ wc
Hello. I typed this line. I typed and typed. I wondered, as I typed, how many words I was typing.
Tis wondrous that as I typed, bash piped.
<Ctrl+D>
4 28 143
Ex:
Standard input is the terminal, by default. The following redirections are possible:
18
Use streams, pipes and redirects
Read input from the terminal:
Read input from file with <. standard input anonymous: wc does not know file name which it is reading from.
[jack@foo jack]$ wc < /etc/passwd
46 62 2010
Ex:
Read input from a program using the pipe redirection. Here cat is piping its output to wc.Ex:
[jack@foo jack]$ cat /etc/passwd | wc
46 62 2010
Read input from script or cmdline. Operator << is traditionally followed by EOF, but any letters can be used.
When a line is found which consists only of EOF, that's the end of the input. This is called a “here document”.
Ex:
[jack@foo jack]$ wc << EOF
> Hello
> There are
> Four lines
> I think
> EOF
4 7 35
20. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Command pipelines (|)
Pipeline – Ability to join input and output of processes together.
To set up a pipe use pipe symbol | between cmds that generates output.
Generally, data piped is text, but its possible to join far too many processes together.
20
Use streams, pipes and redirects
Counting how many unique words appear in the fortune cookie database.Ex:
$ ls /usr/share/games/fortune/* | grep -v '.' | xargs cat |
sed 's/[^a-zA-Z]+/ /g; s/^ *// ' | tr 'A-Z ' 'a-zn' |
sort | uniq | wc -l
28234
ls lists files in fortune cookie directory. grep v removes files that have a dot in the name.
xargs runs cat with all of the file names on its command line. cat prints the contents of the files.
sed edits the stream replacing anything that is not AZ and az with a space, then removes leading spaces.
tr converts everything to lowercase. sort sorts the words in alphabetical order.
uniq removes the duplicates. wc says how many lines there were in its input.
Pipes can be chained as needed, and can also be combined with redirection:
who | fgrep bob | wc -l > bob.sessions
It’s even possible to intermix pipes and redirection! Just keep streams straight:
who 2> who.errors | fgrep bob 2>&1 | wc -l
21. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
tee – divert a copy to a file
tee is like a teepiece for pipes (or T piece).
tee takes one argument, a filename, and will feed all input from stdin to file, simultaneously feeding
output to stdout.
tee forks its input stream, sending one copy to file on disk, and another copy to stdout
By default tee is like redirection > and overwrites contents in the files specified. To apend use tee -a.
21
Use streams, pipes and redirects
tee can save the results of a command in a file while view them on the terminal.Ex:
# ifconfig | tee current-netconf
# route | tee current-routes
tee catches the output of grep in resultsfile, and wc counts it.Ex:
$ ls -lR /etc | grep host | tee resultsfile | wc -l
$ ls -lR /etc | grep host | tee /dev/tty | wc -l
tee -a does not overwrite current contents of a file. In scripts is useful for appending results to log files.Ex:
$ rpm -hiv ppp-2.4.1-7.i386.rpm 2>&1 | tee -a install-log networklog
Recording results of loading a kernel module by reading kernel message buffer with dmesg.
The results are also displayed on the terminal.
Ex:
# date | tee -a log-file
# dmesg -c > /dev/null
# modprobe ppp_generic | tee -a log-file
# dmesg -c | tee -a log-file
22. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
Command substitution – $(command) and `command`
Command substitution
- grab standard output of a command and put it on the command line of another command.
22
Use streams, pipes and redirects
grep and cut commands conspire here to find the name server which is in use.
This is then entered into an environment variable.
Ex:
$ cat /etc/resolv.conf
search example.com
nameserver 192.168.44.2
$ grep nameserver /etc/resolv.conf
nameserver 192.168.44.2
$ grep nameserver /etc/resolv.conf | cut -d ' ' -f 2
192.168.44.2
$ NAMESERVER=`grep nameserver /etc/resolv.conf | cut -d ' ' -f 2`
$ echo $NAMESERVER
192.168.44.2
Forms `command` and $(command) are equivalent.
Quote: `…` is backward quote –difficult to distinguish from regular quote (apostrophe), so some prefer the form $(...)
Rather than using /usr/bin/ftp we use `which ftp`Ex:
$ rpm -qif `which ftp`
$ basename `which ftp`
$ dirname `which ftp`
23. CoreLinuxforRedHatandFedoralearningunderGNUFreeDocumentationLicense-Copyleft(c)AcácioOliveira2012
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,changingisallowed
xargs
xargs - expands its standard input to be arguments to the command it is given.
23
Use streams, pipes and redirects
generate a list of files with grep, and then read files with less. The actual command run is less file1 file2 ...Ex:
grep -l hello /etc/* | xargs less
grep -l root /etc/* 2>/dev/null | xargs wc
The following commands are equivalent:Ex:
echo one two three | xargs rm
rm ` echo one two three `
rm one two three
xargs is often used to handle a list of file names generated by another command.
xargs is frequently used with find. find finds the files, and xargs starts up command that handles the file.
find regular files that have not been accessed for more than 30 days, and removes themEx:
find /tmp -type f -atime +30 | xargs rm
find /tmp -type f -atime +30 -print0 | xargs -0 rm