#!/bin/bash # # This is a further example of how you can make a program that acts as a # typical filter program, BUT will also decompress any *.gz files that are # passed as arguments. This is useful for creating log-processing scripts. # # Cameron Kerr # 19 March 2008 # # Released under the Public Domain # # Note: Normally, you might just use something like the following, where # filter-script is the script that calls a particular filter-prog: # filter-prog "$@" | ... # which will work for the following examples # ... | filter-script | ... # filter-script < file # filter-script file ... # but will not work correctly for # filter-script file file2.gz ... # # Note2: I'm using cat here, which is generally unoptimal, but in this case # its worth it to make the function get its input from stdin if needed. # # Note3: I'm using 'file' to determine the type of file we're dealing with, # rather than its extension. # # Note4: I've only really tested this on Mac OS X, and a little bit on Linux. # Please report bugs. # # Note5: You can also specify - as an input file (this is common practice). # And like other programs (eg. cat) you can specify it multiple times. # Pass this function "$@", which should be all the files (or none) that the # user wishes to get the input from. # get-lines() { if [ $# -eq 0 ]; then cat else for file in "$@"; do if [ -r "$file" ]; then magic=$(file -b -- "$file") case "$magic" in 'gzip compressed data'*) gzip -dc -- "$file" ;; 'bzip2 compressed data'*) bzip2 -dc -- "$file" ;; "compress'd data"*) uncompress -dc -- "$file" ;; *) cat -- "$file" ;; esac elif [ x"$file" = x- ]; then # [ - = - ] is bad, hence x cat else echo "$file: No such file or directory, or no permission to read." >&2 fi done fi } # Testing get-lines "$@" | wc -l