Skip to content

Instantly share code, notes, and snippets.

@jpickwell
Created November 28, 2023 17:46
Show Gist options
  • Save jpickwell/44c822765432c458926cef9c9b514a31 to your computer and use it in GitHub Desktop.
Save jpickwell/44c822765432c458926cef9c9b514a31 to your computer and use it in GitHub Desktop.
POSIX Shell collapse_string function.
#!/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