I'm learning bash redirection. I expect the following code to do the equivalent of ls | grep foo | grep bar
.
#!/bin/bash
{
{
ls | grep foo
} 2>&1 1>&4 | grep bar
} 4>&1
This matches foo but not foo and bar. I thought this will work since 2>&1
copies pipe in fd 1 to fd 2, and then we reset fd 1 to stdout.
Can you fix this code while keeping the braces(contexts)? If I remove 2>&1 1>&4
it works as expected. But I would like to learn.
I think on the left side of pipe | it only expects stdout so even if I copy the pipe to fd 2, it will still only look for fd 1 on the left side of pipe.
Refer: https://wiki.bash-hackers.org/howto/redirection_tutorial#an_example
In the referenced link above, there is a diagram where fd 2 of cmd1 points to fd 0 of cmd3. I'm trying to verify this using my example.
ls
output (unlike say,zsh
, where multiple redirections could be used to send the same output to multiple commands), so since you have only one invocation ofls
in your script, only one ofls | grep \~; ls | grep sh$
would be correct. – muru Feb 1 at 6:24ls | grep \~ | grep sh$
– Logan Lee Feb 1 at 6:56