This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatgz
executable file
·75 lines (64 loc) · 2.04 KB
/
batgz
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env bash
# A bash script to display the contents of a gzip-compressed file using the `bat` utility.
# The script takes the filename of the compressed file as a command-line argument and
# passes any additional arguments to `bat`.
# Exit immediately if a command exits with a non-zero status
set -o errexit
# Improve output when invoked with `bash -x`
export PS4='+|${BASH_SOURCE##*/} ${LINENO}${FUNCNAME[0]:+ ${FUNCNAME[0]}} | '
function usage()
{
echo "Usage: $0 [bat options] filename.gz"
echo
echo "Examples:"
echo " $0 example.gz # Display the contents of example.gz with default options"
echo " $0 -r 10:20 example.gz # Display lines 10 to 20 of example.gz"
}
# Check if the script was called with at least one argument
if [[ $# -lt 1 ]]; then
usage
exit 1
fi
# Parse the command-line arguments
bat_options=()
filename=
while [[ $# -gt 0 ]]; do
case $1 in
-*)
# Collect any additional bat options
bat_options+=("$1")
shift
;;
*)
if [[ -e "$1" ]]; then
# Set the filename
filename="$1"
shift
else
# Pass the argument to bat
bat_options+=("$1")
shift
fi
;;
esac
done
# If no filename was found, print the usage information and exit with an error status
if [[ -z "$filename" ]]; then
usage
exit 1
fi
# Check if the specified file exists
if [[ ! -e "$filename" ]]; then
echo "Error: file '$filename' not found"
exit 1
fi
# If a null byte is found, add the '--show-all' option to bat_options, which will cause bat
# to display all bytes, including non-printable characters, when displaying the contents of the file.
# Note:
# `set -o pipefail` is not used, because zcat will be signaled by grep with SIGPIPE on first hit
if zcat "$filename" | LANG=C grep --quiet --max-count=1 --text --perl-regexp '\x00'; then
bat_options+=("--show-all")
fi
# Display the contents of the file using bat
# Pass the bat options and the filename to bat
zcat "$filename" | bat "${bat_options[@]}" --file-name="$filename"