Skip to content

Instantly share code, notes, and snippets.

@obfusk
Last active December 17, 2015 17:39
Show Gist options
  • Save obfusk/5647380 to your computer and use it in GitHub Desktop.
Save obfusk/5647380 to your computer and use it in GitHub Desktop.
bash functions (hereby public domain)
# Usage: canonpath <path>
# No physical check on the filesystem, but a logical cleanup of a
# path.
# Uses perl.
function canonpath ()
{ perl -MFile::Spec -e 'print File::Spec->canonpath($ARGV[0])' "$1"; }
# Usage: die <msg(s)>
function die () { echo "$@" >&2; exit 1; }
# Usage: grep0 [<arg(s)>]
# Runs grep <arg(s)> but returns 0 if grep returned 0 or 1; and 1 if
# grep returned something else. Thus, only returns non-zero if grep
# actually failed, not if it simply found nothing.
function grep0 () { grep "$@" || [ "$?" -eq 1 ]; }
# Usage: head_neg <K>
# Print all but the last $K lines of STDIN, like GNU head -n -$K.
function head_neg ()
{ # {{{1
local -i k="$1" n i ; local lines=() line
while IFS= read -r line; do lines+=( "$line" ); done
n="$(( ${#lines[@]} - k ))"
for (( i = 0; i < n; ++i )); do printf '%s\n' "${lines[i]}"; done
} # }}}1
# Usage: lock <file> [<target>]
# Creates lock file using ln -s; target defaults to $$; dies if ln
# fails and message doesn't contain 'exists'.
function lock ()
{ # {{{1
local x="$( ! LC_ALL=C ln -s "${2:-$$}" "$1" 2>&1 || echo OK )"
if [ "$x" != OK ]; then
[[ "$x" != *exists* ]] && die "locking failed -- $x"
return 1
fi
} # }}}1
# Usage: original_files_info <path> <to>
# Lists null-separated mode:owner:group:time:path of the original
# files in $path for all files in $to (e.g. for $to/some/file we get
# the info of $path/some/file).
# TODO: how best to handle failures?
function original_files_info ()
{ # {{{1
local path="$( canonpath "$1" )" to="$2" file
find "$to" -printf '%P\0' | while IFS= read -r -d '' file; do
stat --printf '%a:%U:%G:%.Y:%n\0' -- "$path/$file"
done
} # }}}1
# Usage: pipe_chk [<msg(s)>]
# Checks ${PIPESTATUS[@]} and dies if any are non-zero.
function pipe_chk ()
{ # {{{1
local ps=( "${PIPESTATUS[@]}" ) x
for x in "${ps[@]}"; do
[ "$x" -eq 0 ] || die 'non-zero PIPESTATUS' "$@"
done
} # }}}1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment