29 8 月 2012

xargs

Linux xargs utility introduction

xargs – Divert STDIN to Argument of the following command

xargs is an utility on Unix and most Unix-like operating systems used to build and execute command lines from standard input, i.e. xargs divert standard input to Argument of the following command. The default command is echo if no other commands follow.

echo, a non-filter command, can be used for test as follow:

[geego@testbed ~]$ ls | echo

[geego@testbed ~]$ ls | xargs echo
existing_file expand_test ls.txt ls_err.txt permission.txt stdio tee_test test u niq_test
[geego@testbed ~]$ ls | xargs
existing_file expand_test ls.txt ls_err.txt permission.txt stdio tee_test test u niq_test
[geego@testbed ~]$ ls | wc -l
9
[geego@testbed ~]$ ls | xargs wc -l
0 existing_file
2 expand_test
0 ls.txt
1 ls_err.txt
0 permission.txt
wc: stdio: Is a directory
0 stdio
583 tee_test
6 test
0 uniq_test
592 total
[geego@testbed ~]$ wc -l *
0 existing_file
2 expand_test
0 ls.txt
1 ls_err.txt
0 permission.txt
wc: stdio: Is a directory
0 stdio
583 tee_test
6 test
0 uniq_test
592 total
[geego@testbed ~]$

For advanced STDOUT/STDERR, each computer language possesses its unique function to output data to STDOUT/STDERR. The following JAVA programming shows how to deal with programming output:

testbed@geego geego$ cat STDx.java
public class STDx
{
public static void main ( String[] args)
{
System.out.println(”This is from STDOUT” );
System.err.print(”This is from STDERR”);
}
}

testbed@geego geego$ javac STDx.java
testbed@geegogeego$ java STDx
This is from STDOUT
This is from STDERR
testbed@geegogeego$ java STDx>stdout 2>stderr
testbed@geegogeego$ cat stdout
This is from STDOUT

testbed@geegogeego$ cat stderr
This is from STDERR

Homework

1. There exist one existing file named foo and one non-existing file named bar in current directory. What is the output of “wc-1” in “ls foo bar | wc –l”? The point is how pipeline diverts one command output to another command input. STDOUT will be diverted to another command whereas STDERR is only output to screen display.

2. Please execute “echo “alt000a” >cmd_test” and make cmd_test executable, then observe the result.
Holding on the Alt key and type in hex code outputs ASCII characters. Here 000a refers to “\n” (LF) so it only changes lines continuously when executing cmd_test.

3. Log in root and execute “find / -print” in terminal tty1 (use the command tty to show the current terminal) then redirect STDOUT and STDERR to /dev/tty2. See the reflection of terminal tty2.

Reference:
Stevens, W. Richard. 1992.Advnaced Programming in the UNIX environment ISBN 0-201-56317-7