Wednesday, January 29, 2014

Unix Shell Scripting – Grouping Commands ()

- Occasionally in Unix Shell scripting we may need to group multiple commands together and treat them as single command

Why that is needed ?  Lets validate the requirements examples for doing so

- We may need to run the command in background (via the & command)

- We may need to redirect the output of the command to a file or other program (or command)  (using > or |)

- If you wish to apply the same action (in the example below output to other file using >) to several consecutive programs(in the example below echo & date programs), it is possible to group them together and apply the action to the group as below

Without Grouping-

[oracle@rac1 ~]$ echo Todays date is > DateOutput
[oracle@rac1 ~]$ date >> DateOutput
[oracle@rac1 ~]$ more DateOutput
Todays date is
Thu Jan 30 08:24:23 IST 2014

With Grouping – Checking the parentheses used to group commands echo & date, > before the date in second line(highlighted in yellow) shows that the you have opened the parentheses for grouping and waiting for other commands.

Check the output is same from the above(in which programs as executed individually) and below (programs are grouped together using parentheses () )

[oracle@rac1 ~]$ (echo Todays date is
> date ) > DateOutput
[oracle@rac1 ~]$ cat DateOutput
Todays date is
Thu Jan 30 08:29:03 IST 2014

Instead you can use the ; (Line COntroller) character to separate the commands and mention the commands in the same line as below

[oracle@rac1 ~]$ (echo User Logged is $LOGNAME today at ;date) > UserLogged

[oracle@rac1 ~]$ cat UserLogged
User Logged is oracle today at
Thu Jan 30 08:48:04 IST 2014

No comments:

Post a Comment