help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Use of |&


From: Greg Wooledge
Subject: Re: Use of |&
Date: Mon, 13 Feb 2023 10:59:06 -0500

On Mon, Feb 13, 2023 at 04:47:31PM +0100, alex xmb ratchev wrote:
> On Mon, Feb 13, 2023, 4:45 PM goncholden <goncholden@protonmail.com> wrote:
> > On Monday, February 13th, 2023 at 3:37 PM, Greg Wooledge <
> > greg@wooledge.org> wrote:
> > > I don't use it, nor do I recommend it. I'd prefer to stick with 2>&1 |
> > >
> > > because that'll work everywhere, and won't confuse the reader (as much,
> > > one hopes).
> >
> > Does it make sense to use 'cmd 2>&1 | getline var' when calling getline ?
> > Or doing 'cmd | getline var' is good enough ?

It depends on whether you want to parse *just* standard output, or both
standard output and standard error.

Also, I don't know what "getline var" is doing there.  If it's similar
to "read -r var", you should understand that the variable is being set
inside a subshell, and therefore won't be available to the rest of
the script after that pipeline ends.

> u talk about bash |& or gawk |&
> getline is awkism

If you're mixing bash commands and awk commands, without actually
showing the syntax correctly, then all bets are off.

Here's an example of 2>&1 using bash only.  We'll start with a command
that generates both stdout and stderr:

unicorn:~$ ls -l .bashrc nosuchfile
ls: cannot access 'nosuchfile': No such file or directory
-rwxr-xr-x 1 greg greg 2814 Feb  6 15:09 .bashrc*

As you can see here, there's an error message (which we assume is going
to stderr), and then some normal output, which we assume is going to stdout.

If we add a piped filter:

unicorn:~$ ls -l .bashrc nosuchfile | grep rwx
ls: cannot access 'nosuchfile': No such file or directory
-rwxr-xr-x 1 greg greg 2814 Feb  6 15:09 .bashrc

We still see the error message, because stderr did not go into the pipeline,
and therefore wasn't filtered.  So, we see the error message written by
"ls" directly to the terminal, and then we see the output of "grep rwx",
also written to the terminal.

Adding 2>&1, we get:

unicorn:~$ ls -l .bashrc nosuchfile 2>&1 | grep rwx
-rwxr-xr-x 1 greg greg 2814 Feb  6 15:09 .bashrc

This time, both the error message *and* the normal output went into the
pipeline to be filtered.  The "grep rwx" filter only prints the normal
output, not the error message.

Using |& instead of 2>&1 | is the same thing, except that it only works
in certain versions of bash.

I can't help you with awk unless I see an actual command.  I know some awk,
but I'm not an expert with it.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]