terom@60: #!/bin/bash terom@52: # terom@52: # Utility functions terom@52: terom@52: ### Command execution terom@52: ## Execute command, possibly logging its execution. terom@52: # terom@52: # cmd $cmd... terom@52: # terom@52: # Fails if the command returns an error exit code. terom@52: function cmd { terom@52: log_cmd "$@" terom@52: terom@83: "$@" || die "Failed: $@" terom@52: } terom@52: terom@66: ## Execute command as a test, logging its execution at log_cmd terom@66: # terom@66: # cmd_test $cmd... && ... || ... terom@66: # terom@66: # Fails if the command returns an error exit code. terom@66: function cmd_test { terom@66: log_cmd "$@" terom@66: terom@66: "$@" terom@66: } terom@55: ## Execute command, prefixing its output on stdout with given indent prefix. terom@55: # terom@55: # indent " " $cmd... terom@55: # terom@55: # Output is kept on stdout, exit status is that of the given command. terom@52: function indent () { terom@85: local indent="$1"; shift terom@52: terom@52: "$@" | sed "s/^/$indent/" terom@52: terom@52: return ${PIPESTATUS[0]} terom@52: } terom@52: terom@52: terom@52: ### FS utils terom@82: # Create dir if not exists. terom@52: function ensure_dir { terom@85: local dir="$1" terom@52: terom@85: if [ ! -d "$dir" ]; then terom@52: log_warn "Creating output dir: $dir" terom@85: cmd mkdir "$dir" terom@52: fi terom@52: } terom@52: terom@82: ## Output absolute path terom@52: # terom@52: # abspath $path terom@52: # terom@82: # XXX: improve...? terom@52: function abspath () { terom@85: local path="$1" terom@52: terom@82: echo "$SRV/$path" terom@52: } terom@52: terom@98: function _list { terom@98: local glob="$1" terom@98: local test="$2" terom@98: local prefix="$3" terom@98: terom@98: for file in $glob; do terom@98: [ $test "$file" ] || continue terom@98: [ -n "$prefix" ] && file="${file#$prefix}" terom@98: terom@98: echo -n "$file " terom@98: done terom@98: } terom@98: terom@98: ## List names of all files in dir terom@98: function list { terom@98: _list "$1/*" '-e' ${2:-$1/} terom@98: } terom@98: terom@69: ## List names of files in dir: terom@69: # terom@98: # list_files $dir terom@69: # terom@69: function list_files { terom@98: _list "$1/*" '-f' ${2:-$1/} terom@69: } terom@69: terom@87: ## List names of dirs in dir: terom@82: function list_dirs { terom@98: _list "$1/*" '-d' ${2:-$1/} terom@98: } terom@87: terom@98: ## List names of any files underneath dir or file: terom@98: function expand_files { terom@98: _list "$1 $1/**" '-f' '' terom@52: } terom@95: terom@95: ## Get current unix (utc) timestamp terom@95: function unix_time { terom@95: date +'%s' terom@95: }