File: dog.sh 1 #!/bin/sh 2 3 # The MIT License (MIT) 4 # 5 # Copyright © 2020-2025 pacman64 6 # 7 # Permission is hereby granted, free of charge, to any person obtaining a copy 8 # of this software and associated documentation files (the “Software”), to deal 9 # in the Software without restriction, including without limitation the rights 10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 # copies of the Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice shall be included in 15 # all copies or substantial portions of the Software. 16 # 17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 # SOFTWARE. 24 25 26 # dog [options...] [paths/URIs...] 27 # 28 # Dog fetches data from the named sources given to it, whether these are 29 # filenames or URIs. Single dashes stand for standard input, and can't be 30 # used more than once. When no names are given, stdin is read by default. 31 32 33 # fail quits the script right after showing the message given, using 34 # exit code given as its 2nd arg 35 fail() { 36 printf "\e[31m%s\e[0m\n" "$1" > /dev/stderr 37 exit "${2:-1}" 38 } 39 40 # when no args are given, just show the help message and quit 41 if [ $# -eq 0 ]; then 42 exit $? 43 fi 44 45 case "$1" in 46 -h|--h|-help|--help) 47 awk '/^# +dog /, /^$/ { gsub(/^# ?/, ""); print }' "$0" 48 exit 0 49 ;; 50 esac 51 52 # ensure single dashes aren't used multiple times 53 dashes=0 54 for name in "$@"; do 55 if [ "${name}" = "-" ]; then 56 if [ "$dashes" -gt 0 ]; then 57 fail "can't use stdin (single-dash) more than once" 1 58 fi 59 dashes=1 60 fi 61 done 62 63 for name in "$@"; do 64 case "${name}" in 65 # handle a dash by reading from stdin 66 -) cat || exit $?;; 67 68 # handle URIs 69 dict://*|file://*|ftp://*|ftps://*|gopher://*|gophers://*|\ 70 http://*|https://*|rtmp://*|rtsp://*|scp://*|sftp://*|\ 71 smb://*|smbs://*|telnet://*|tftp://*) 72 curl -s -L "${name}" || fail "failed to fetch URI ${name}" $?;; 73 74 # handle data-URIs 75 data:*) { 76 printf "%s" "${name}" | sed -E 's-^data:.{0,50};base64,--' | 77 base64 -d 78 } || fail "failed to decode data-URI ${name}" $?;; 79 80 # handle files and bytes-mode data-URIs 81 *) cat "${name}" || fail "failed to open file ${name}" $?;; 82 esac 83 done