0

I want to only have a process called if there actually is a STDERR present, but I don't know how to evaluate if one is actually present or not. This code:

errtest() {
  kubectl get namespace -A
  kubectl get namespace -A 2> >(echo "why am I here")
}
> errtest

Output:

NAME                               STATUS   AGE
2c74fd3b89e64077afd34d8ab8af4f09   Active   10d
845d1f1c71ed42c8b9e4c780992a95c0   Active   367d
why am I here
NAME                               STATUS   AGE
2c74fd3b89e64077afd34d8ab8af4f09   Active   10d
845d1f1c71ed42c8b9e4c780992a95c0   Active   367d

Obviously the first time shows that the output doesn't have any error, so the primary question is, why is "why am I here" showing? That seems counterintuitive.

The secondary question is, in this case, how could I identify the STDERR so that I can work on context? Something like:

      kubectl get namespace -A 2> >(if [[ -z STDERR ]]; then echo "there is an error"; fi)

1 Answers1

0

So the understanding needed to resolve this issue is what is being passed to

>(echo "why am I here")

.. specifically, a resource which can be read line by line. AFAIK the resource is not something that can be (easily) passed further. Or referenced as a variable. This was the solution I had:

errtest() {
  random_variable="hello this works"
  # yes you can pass parameters as well..
  kubectl get namespace -A 2> >(errtest_if $random_variable)
}
errtest_if() {
  while read line; do
    echo "parameter 1 is $1"
    echo $line          #<< first line of the error
    #evaluate it if desired
    echo "looks like you are not logged in"
    #maybe call something else if desired
#break if you only need to know there _is_ an error
break

done } > errtest

NOTE: as far as using ifne I chose not to because a) it wasn't installed on my linux and b) if that's true for me then it'll be true for someone else.

  • Small problem with while read line: if input doesn't end with a newline, any text after the last newline won't be processed by the loop. – muru Apr 22 '22 at 21:24
  • 1
    In another question, you say you're using zsh. This is not available by default on all Linux systems. Would that not be the same issue as using ifne from the moreutils package? ifne is, after all, a utility made specifically for solving the issue that you have. – Kusalananda Apr 22 '22 at 21:39