Pages

Thursday 25 August 2011

All About PIPESTATUS internal Variable in Linux


This is bit advanced topic, people new to Shell scripting and administration can skip this post.
Today I have come across an awesome internal variable to get the piped command output status. Let me explain a scenario which I faced in automating a task.
I am executing the following command to get two entries from password file, one entry is google and other  term is vijay. The out put should verify both exit status..
cat /etc/passwd | grep google | grep vijay
Let me explain why I require both values.  We create users per project in our FTP server where a user account should not repeat again in a same project(but can be created in different project as username_porjectname). The above command have some drawbacks such as
1)If both the variables present then only i get zero as exit status.
2)If one variable is present then i will get different status, which is of no use..
so how to resolve this issue?
Use inbuilt PIPESTATUS variable for this.
How to use this PIPESTATUS in Scripting?
PIPESTATUS is a array variable which contain the exit status of each command in piped commands. So

$PIPESTATUS[0] This will contain first command exit status

$PIPESTATUS[1] This will contain second command exit status

$PIPESTATUS[2] This will contain third command exit status and so on..
For example see below commands
cat /etc/passwd | grep google | grep vijay
now $PIPESTATUS[0] contains exit status of cat /etc/passwd command
$PIPESTATUS[1] contains exit status of grep google command
$PIPESTATUS[2] contains exit status of grep vijay command
so how we can use this in scripting?
instead of check exit status of whole piped command we will take each command status for meaning full way with an if loop with each status for each if loop..

No comments:

Post a Comment

Twitter Bird Gadget