File: bytes.sh 1 #!/bin/sh 2 3 # The MIT License (MIT) 4 # 5 # Copyright © 2024 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 # bytes [files/URIs...] 27 # 28 # Fetch data from the named sources given to it, whether these are 29 # filenames or URIs. Single dashes stand for standard input, and can be 30 # used more than once. When no names are given, stdin is read by default. 31 # 32 # Bytes from all sources are concatenated/appended with no changes. 33 34 35 # fail quits the script right after showing the message given, using 36 # exit code given as its 2nd arg 37 fail() { 38 printf "\x1b[31m%s\x1b[0m\n" "$1" > /dev/stderr 39 exit "$2" 40 } 41 42 # when no args are given, just read from stdin and quit 43 if [ $# -eq 0 ]; then 44 cat 45 exit $? 46 fi 47 48 # handle leading options 49 case "$1" in 50 -h|--h|-help|--help) 51 # show help message, extracting the info-comment at the start 52 # of this file, and quit 53 awk '/^# +bytes/, /^$/ { gsub(/^# ?/, ""); print }' "$0" 54 exit 0 55 ;; 56 esac 57 58 # ensure single dashes aren't used multiple times 59 dashes=0 60 for a in "$@"; do 61 if [ "$a" = "-" ]; then 62 if [ "$dashes" -gt 0 ]; then 63 fail "can't use standard input (single-dash) more than once" 1 64 fi 65 dashes=1 66 fi 67 done 68 69 for a in "$@"; do 70 case "$a" in 71 -) 72 # handle a dash by reading from stdin 73 cat || exit $? 74 ;; 75 76 data:*) 77 # handle data-URIs 78 (printf "%s" "$a" | sed 's-^.*,--1' | base64 -d) || \ 79 fail "failed to decode data-URI $a" $? 80 ;; 81 82 dict://*|file://*|ftp://*|ftps://*|gopher://*|gophers://*|\ 83 http://*|https://*|rtmp://*|rtsp://*|scp://*|sftp://*|\ 84 smb://*|smbs://*|telnet://*|tftp://*) 85 # handle URIs 86 curl -s -L "$a" || fail "failed to fetch URI $a" $? 87 ;; 88 89 *) 90 # handle files 91 cat "$a" || fail "failed to fetch file $a" $? 92 ;; 93 esac 94 done