I don’t like the truncate command line tool. I use it way to often to want to type the flags. And I have never, ever used it for anything but to completely truncate a file.

So I hacked up my own little trunc-func.

    #!/bin/bash
    function delete {
        printf "" > $1
        echo "Truncated $1"
    }

    function keep {
        echo "File untouched"
    }

    if [ -z "$1" ]; then
        echo "No file specified"
        exit
    fi
    read -n1 -p "Truncate file? [yN]" delete
    printf "\n"
    case $delete in
        y|Y) delete $1 ;;
        *) keep ;;
    esac

Example:

    $ cat afile.code
    Code
    And other stuff
    $ trunc afile.code
    Truncate file? [yN]<press y>
    Truncated afile.code
    $ cat afile.code
    $ 

And just to check, here’s a little performance test. I create a huge file and then truncate it.

    $ cat /dev/random > tmp&
    [1] 85326
    # let this run for a while
    $ kill 85326
    [1]  + 85326 terminated  cat /dev/random > tmp
    $ ls -l tmp
    -rw-r--r--  1 hjort  staff   7.5G Mar  8 16:43 tmp
    $ date ; wc tmp ; date
    Tue Mar  8 16:46:28 CET 2016
     31369335 243126635 8031531008 tmp
    Tue Mar  8 16:47:44 CET 2016

So we have a 7.5 GB file here. That’s about as big as anything I ever touch in my file system at once. It took over a minute to do a wourd count in it. Let’s make sure it doesn’t take forever to truncate. I will print the date, truncate, hit y quick, and the print the date again.

    $ date ; trunc tmp ; date
    Tue Mar  8 16:49:12 CET 2016
    Truncate file? [yN]y
    Truncated tmp
    Tue Mar  8 16:49:13 CET 2016

It took about a second, including me hitting a key. I’d say that’s good enough.

Continous development (or not) on GitHub.

P.S. Aliases are less fun