Exit Full View

Lazy Redirector

Some of the best ideas are the simplest, and here's an example...

When using linux/unix command line, a common mistake is to attempt to read a file, process it and redirect the results to the same file :

sort mylist.txt > mylist.txt

This won't work though (as mylist.txt is overwritten before the sort process even starts).

Inspired by a program called holdon, by Richard Whitty here's my solution :

In a file called "lazyredirect" somewhere on your PATH :

#!/bin/bash
#
# Takes stdin, and redirects is to a file once stdin has been closed (i.e. after the
# process that generates the input is complete)
#
# Usage :
# lazyredirect FILE
#
# Example :
# sort mylist.txt | lazyredirect mylist.txt
#

TMP_FILE="$1-lazyredirect~$$~"

cat > "${TMP_FILE}"
mv -- "${TMP_FILE}" "$1"

Now to sort that file :

sort mylist.txt | lazyredirect mylist.txt