license headers
[log-quiet] / logq-function
1 #!/bin/bash
2 # Copyright (C) 2014-2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 logq () {
16 local help="Usage: logq [-h|--help] COMMAND [ARG...]
17
18 Log Quietly. Run COMMAND with ARGs, log to temp file. Output return code,
19 command, and log path. Tail log if there is a failure.
20 Follows output format of logsave."
21
22 if [[ $1 == --help || $1 == -h ]]; then
23 echo "$help"
24 return
25 fi
26 if [[ $# == 0 ]]; then
27 echo "error: need 1 or more arguments
28 $help"
29 return 1
30 fi
31
32 # deliniate arguments, so spaces aren't ambiguous
33 local index=0
34 local x prettycommand
35 for x in "$@"; do
36 prettycommand+="[$index]$x "
37 index=$(( index+1 ))
38 done
39
40 local file="$*"
41 file="$(mktemp -d)/${file//[[:space:]\/]/_}"
42 # give us ~20 char filename max
43 file="${file:0:40}"
44
45 printf "%s\n%s\n\n" "Log of $prettycommand" "$(date)" >"$file"
46
47 if [[ $- != *x* ]]; then
48 echo "log $file = $@"
49 fi
50
51 # we will propagate any errors
52 local logq_ret=$(
53 set +e
54 trap ERR
55 "$@" &>> "$file"
56 echo $?
57 )
58 printf "\n%s\n%s\n" "$(date)" "----------------" >> "$file"
59
60 if [[ $logq_ret != 0 ]]; then
61 x="tail -n 100 $file"
62 if [[ $- != *x* ]]; then
63 echo "logq failure. $x :"
64 fi
65 $x
66 fi
67 return $logq_ret
68 }