Friday, 24 June 2011

Pipes and Shell Arithmetic


Pipes
Pipe is powerful utility in Linux which allows the user to execute a chain of commands together. Chaining is done in such a way that the output of one process (stdout) is the input to another (stdin).The symbol | is the Unix pipe symbol that is used on the command line. 

What it means is that the standard output of the command to the left of the pipe gets sent as standard input of the command to the right of the pipe. Note that this functions a lot like the > symbol used to redirect the standard output of a command to a file. However, the pipe is different because it is used to pass the output of a command to another command, not a file.
File:Pipeline.svg
Figure clearly illustrates the fact that the output of the program 1 is the input to program 2 and output of program 2 is input to the program 3.

For example : 

$ ls | grep test

The ls command will fetch the contents of the current directory and list them. The output of the ls command is input to grep. Hence grep will search for the lines containing the word test.



Another example.


Here the ls output is input to head which considers only first 20 lines of ls output and then passes it to sort. sort performs arranges the lines alphabetically in the reverse order because of the -r argument passed to it.

Shell Arithmetic 


Shell Arithmetic is carried out using the command expr. Its very simple but can become a headache for large expressions. 


Syntax:
expr op1 math-operator op2

Examples: 
$ expr 2 + 3 # Note the space between the operands and operator

$ expr 2 +3  # Error
$ expr 3 - 1
$ expr 20 / 2
$ expr 23 % 3  
$ expr 20 \* 3  
$ echo `expr 6 + 3`


Note:
expr 10 \* 3 - Multiplication uses \* and not * since its wild card.


Parameter substitution is a shortcut to avoid writing expr again and again.

1. Use $(( expression)) instead.
For example:
$ echo $((3+4))
$ echo $(( 3 + 4 ))
Note that here the spaces between the operands and the operators does not matter. ( Thank Lord! )

2. A variable can also be addressed as ${var}
$ echo ${var}
outputs the same value as 
$ echo $var

3. A variables length can be accessed by ${#var}
$ echo ${#var} #assume var=Hello
$ 5

4. ${var:pos} substrings the variable starting at pos.
$ echo ${var:2}  #assume var=Hello
$ llo



5.${var:pos:len} substrings the variable starting at pos with a max length of len.
$ echo ${var:2:2}
$ ll



6.${var/pattern/replacement} replaces pattern with replacement once.
$ echo ${var/l/L}
$ HeLlo


7. ${var//pattern/replacement} replaces pattern with replacement globally.
$ echo ${var//l/L}
HeLLo













No comments:

Post a Comment

Popular Posts