Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: detect pipe

On Thu, Jan 28, 2021 at 7:22 PM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
> Sorry to waste everyone's time.

Not necessarily a waste.

A couple of more words on this, particularly on the theme of "tabs -4".

"tabs" adjusts the terminal, and pretty much by definition only for
output, so you should be able to get away with

# Only run "tabs" on terminal stdout
# Close stdin to avoid stealing input
[[ -t 1 ]] && tabs -4 <&-

The next thing to note is that you can use "anonymous" functions in an
alias definition:

alias g='function {
  [[ -t 1 ]] && tabs -4 <&-
  grep --color=always "$@"

This works because words following the closing brace of an anonymous
function become its argument list.  Simpler example:

% alias q='function { print -rl -- "$@" }'
% q a b c

I'd also point out that by using "$@" instead of "$1" "$2" in "g", you
never pass an empty string as the filename to grep.  That means you
don't have to care whether standard input is a pipe; it will read
standard input if there is one argument, and read from $2 (and any
subsequent file names) if there are 2 or more arguments.  The
difference from your original definition is that you don't get "grep:
: No such file or directory" if you pass 1 argument when the standard
input is NOT a pipe.

The last note is that this inlined-function trick does NOT work with
"noglob".  You CANNOT write e.g.

noglob function { print -rl -- "$@" } a* *b

So if you want to introduce noglob, you have to use a real function.
You can still do everything else I mentioned.

_g() {
  [[ -t 1 ]] && tabs -4 <&-
  grep --color=always "$@"
alias g='noglob _g'

Messages sorted by: Reverse Date, Date, Thread, Author