Bash Samples

Find a particular class file in a directory of jar files

 
#!/bin/sh
findclass='ClassFileName'
for f in `ls`
do
  jar tvf $f | grep ${findclass}
  if [ $? = '0' ]
  then
    echo "Found ${findclass} in $f file."
  fi
done
 

Find a particular class file in all jar files

 
#!/bin/sh
findclass='ClassFileName'
for f in `find . -name "*.jar"`
do
  jar tvf $f | grep ${findclass}
  if [ $? = '0' ]
  then
    echo "Found ${findclass} in $f file."
  fi
done
 

Use getopts

 
#--------------------------------------------
# Get options
#--------------------------------------------
while getopts ":a:b:r:" opt
do
  case $opt in
    a)
      alpha=$OPTARG
      ;;
    b)
      beta=$OPTARG
      ;;
    r)
      gamma=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      ;;
    :)
      echo "Option -$OPTARG requires an argument."
      ;;
  esac
done
 

grep Examples

 
# grep one of multiple strings
grep "string1\|string2\|string3"
 
# Inverse grep
grep -v "notThisString"
 

Remove Old Log Files

 
# List log files older than 30 days
find . -type f -mtime +30 -type f -name "*.log" -exec ls -altr {} \;
 
# Remove log files older than 30 days
find . -type f -mtime +30 -type f -name "*.log" -exec rm {} \;
 
# Remove log files older than 3 days
find . -type f -mtime +3 -type f -name "*.log" -exec rm {} \;
 

Comments are closed