Friday, December 5, 2008

'tree' script under Linux/Unix/Cygwin

A simple script to traverse all the directories and do whatever you want. The byproduct is a MS-DOS tree command.
#!/bin/bash

listAll() {
    local f
    local i=$1

    for f in `ls -1`; do    # 1 file per line
        if [ -f "$f" ]; then
            indent $i
            echo "|- $f"
            if [ "$COMMAND" != "" ]; then
                IFS=$oIFS
                $COMMAND "$f"
                IFS=$nIFS
            fi
        elif [ -d "$f" ]; then
            indent $i
            echo "+- $f"
            let i+=$INDENTS
            cd "$f"
            listAll $i
            cd ..
            let i-=$INDENTS
        fi
    done
}

indent() {
    local i=0
    while (( i < $1 )) # or: while [ i -lt $1 ]
    do
        echo -n " "
        let i+=1
    done
}

echo "Usage: shred-tree [-u]"
echo "-u: shred; otherwise just list"
echo

if [ "$1" = "-u" ]; then
    COMMAND="" # put your command here, eg. ls -l
fi

# space delimitered:
oIFS=$IFS   

# \n delimitered:
nIFS='
'

IFS=$nIFS   # For file names containing spaces
INDENTS=3
listAll 0

No comments: