Search My Techie Guy

Wednesday, December 1, 2010

Quick Check - UNIX Scripting (bash/ksh/) One Liners

Example: Display only the file names in a directory - "for loop"
This code can be used to copy, delete or move files, just replace the "echo" command with a "cp", "rm" or "mv" command.
for i in `ls -ltr | awk '{ print $9 }'`;
do
echo $i;
done

Example: Delete all files in a directory except the most recent - "for loop"
#!/bin/bash
DIR=/export/home/nomwesj/
cd $DIR
lastfile=`ls -ltr|tail -1|awk '{print $9}'`
for files in `ls -ltr|grep -v $lastfile|awk '{print $9}'`
do
    echo "Removing File(press Ctrl+C to abort):" $files
    sleep 2
   #rm $files
done

Example: How to "comment out" a block of code in a bash/ksh script
:<<'comment2'
Anything within this
block
will be treated as a comment
comment2

Example: List log files older than (x) days
List logs older than 7 days:
find /export/home/log/* -mtime +7 -exec ls -lrt '{}' \;
Delete logs older than 7 days:
find /export/home/log/* -mtime +7 -exec rm '{}' \;

No comments: