Barney Maccabe Last modified: Mon Mar 1 11:38:58 MST 1999

Solutions for Homework Assignment 1

Problem 1. Write a shell program (script or function) that will report the 10 largest files in a subtree starting from the directory specified as the first argument to the program.

function top10 () { 
     if [ "$1" != "" ] ; then
	find $1 -follow -printf "%s\t%p\n" 2>/dev/null | sort -nr | head 
    else
        echo "missing argument"
    fi
}
    

Notes:

Problem 2. Write a shell program (script or function) that will report all files with the setuid or setgid bit set in a subtree starting from the directory specified as the first argument to the program.

function sets () {
    find $1 -follow -perm +03000 2>/dev/null
}
    

Problem 3. Write a shell program (script or function) that will move all plain files in the current directory that are older than 6 months to subdirectory called old. (This kind of program might be useful if you are managing a collection of mail folders and you want to clean up the folders that you are no longer using actively.)

function mvold () {
    find . -maxdepth 1 -mtime +180 -a ! -name old -exec mv \{} old;
}
    

Notes:

Problem 4. Write a shell program (script or function) that will count the number of files of each type (as defined by the file command) in the current directory and all subdirectories. The output should be sorted by number of files of each type.

function ftypes () {
    find . -follow -exec file -b \{} \; 2>/dev/null | sort | uniq -c \
	| sort -nr
}
    

Notes:

Problem 5. Write a shell program (script or function) that will change the name of each plain file in the current directory to a name that includes the date the file was last modified.

function namemod () {
    for f in * ; do
	mod=`ls -Lld $f | colrm 1 42 | tr ' ' '_'`
	mv $f $mod
    done
}
    

Notes:

Problem 6. Write a shell program (script or function) that will find the first available user id (a user id that is not currently being used according to the information in /etc/passwd) greater than the argument it is passed.

function uidp1 () {
    min=$1
    if [ "$min" == "" ]; then
	min=1000
    fi
    tmp=`mktemp /tmp/XXXXXX`
    if [ $? -ne 0 ]; then
	echo "Can't create temp file, exiting..."
        return
    fi
    cut -d: -f3 /etc/passwd | sort -n > $tmp
    maxuid=`tail -1 $tmp`

    minp1=`expr $min + 1`
    maxp1=`expr $maxuid + 1`

    seq $minp1 $maxp1 | diff - $tmp | grep '<' | head -1 | sed 's/< //'
    rm $tmp
}