|
Five Shell Programming Tips |
|
|
|
|
Written by Hemanshu Patel
|
|
Friday, 04 April 2008 |
|
Page 2 of 2 xargs: Newbies often us loops or variables when xargs would suffice. xargs reads standard input, splits the input by whitepsace (spaces and newlines) and then executes the command you specify with the processed input. The three examples below all delete files in the current working directory matching ‘mess*’ which contain the word ‘Synergy’. However, the third is the simplest and most concise. Its the UNIX solution.Using a variable: [root@mojito ~]# export FILES=`find . -type f -name 'mess*' -exec grep -q 'Synergy' {} \; -print` [root@mojito ~]# rm -f $FILES Using a loop: [root@mojito ~]# for FILE in `find . -type f -name 'mess*' -exec grep -q 'Synergy' {} \; -print` do rm -f $FILE; done Using xargs: [root@mojito ~]# find . -type f -name 'mess*' -exec grep -q 'Synergy' {} \; -print | xargs rm -f read: read is command built into the shell. You can use it to obtain data interactively from a user: [root@mojito ~]# read VAR value [root@mojito ~]# echo $VAR value Or you can use read in scripts like the following. If the following script seems complex, don’t get hung up on the specifics. Just notice how the condition in the while loop is ‘read FILE’ which causes the while loop will continue to loop until the variable FILE is not assigned a new value. [root@mojito ~]# cat logRotate.sh #!/bin/bash find . -type f -name 'mess*.[0-9]' | sort -r | \ while read FILE do NUM=`echo $FILE | awk -F. '{print $3}'` # filename Ex: ./file.$NUM BASE=`echo $FILE | awk -F. '{print $2}'` ((NUM++)) mv -f $FILE .$BASE.$NUM done cp -f messages messages.0 cat /dev/null > messages [root@mojito ~]# ls -l messages* -rw------- 1 root root 107207426 Feb 10 21:00 messages -rw------- 1 root root 107207426 Feb 10 20:58 messages.0 -rw------- 1 root root 107207426 Feb 10 20:57 messages.1 -rw------- 1 root root 107207426 Feb 10 20:57 messages.2 -rw------- 1 root root 107207426 Feb 10 20:55 messages.3 -rw------- 1 root root 107207426 Feb 10 20:55 messages.4 -rw------- 1 root root 107207426 Feb 10 20:55 messages.5 -rw------- 1 root root 107207426 Feb 10 20:51 messages.6 [root@mojito ~]# ./logRotate.sh [root@mojito ~]# ls -l messages* -rw------- 1 root root 0 Feb 10 21:00 messages -rw------- 1 root root 107207426 Feb 10 21:00 messages.0 -rw------- 1 root root 107207426 Feb 10 20:58 messages.1 -rw------- 1 root root 107207426 Feb 10 20:57 messages.2 -rw------- 1 root root 107207426 Feb 10 20:57 messages.3 -rw------- 1 root root 107207426 Feb 10 20:55 messages.4 -rw------- 1 root root 107207426 Feb 10 20:55 messages.5 -rw------- 1 root root 107207426 Feb 10 20:55 messages.6 -rw------- 1 root root 107207426 Feb 10 20:51 messages.7
|