Created
November 28, 2023 17:46
-
-
Save jpickwell/44c822765432c458926cef9c9b514a31 to your computer and use it in GitHub Desktop.
POSIX Shell collapse_string function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
# Disable this error because ShellCheck doesn't understand the conditional | |
# usage of positional arguments. | |
# shellcheck disable=SC2120 | |
collapse_string() { | |
{ | |
if [ $# -gt 0 ]; then | |
# Use positional arguments. | |
echo "$@" | |
elif [ ! -t 0 ]; then | |
# Use piped input. | |
cat < /dev/stdin | |
else | |
# No input. | |
echo '' | |
fi | |
} | tr -d '\a\b\f\r\n\t\v' | |
} | |
# positional example: collapse_string "$(printf '\thello\n \nworld\t')" => 'hello world' | |
# pipe example: printf '\thello\n \nworld\t' | collapse_string => 'hello world' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment