Skip to content

Instantly share code, notes, and snippets.

@mattmc3
Created August 20, 2022 12:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmc3/08600d86ef3cbcb96cf998b53fb4d8f1 to your computer and use it in GitHub Desktop.
Save mattmc3/08600d86ef3cbcb96cf998b53fb4d8f1 to your computer and use it in GitHub Desktop.
Zsh - append piped/redirected input to arg array
# Example to show how to append piped/redirected input to arg array
#
# More info:
# `man test` (lookup -t flag)
# `man zshbuiltins` (lookup set builtin)
#
# piped_input_example
# piped_input_example --flag arg
# piped_input_example --opt1 -x -y -z param1 param2 <<< "zzz"
# echo "abc" | piped_input_example --opt1 -x -y -z param1 param2
# printf "%s\n" abc def | piped_input_example --opt1 -x -y -z param1 param2
function piped_input_example {
local piped=()
if [[ ! -t 0 ]]; then
# handle both <redirected or piped| input
local data
while IFS= read -r data || [[ -n "$data" ]]; do
piped+=($data)
done
fi
echo "regular args ($#): $@"
echo "piped args ($#piped): $piped"
echo "setting new arg array..."
(( $#piped )) && set -- "$@" "$piped[@]"
echo "new arg array ($#): $@"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment