user16541120
user16541120

Reputation:

Can you use grep or sed to remove a particular error message from stderr?

I am running the following command in a script:

kubectl cp -n $OVN_NAMESPACE -c ovnkube-node $ovnkube_node:$save_dir ${WORKDIR}/restore_flows

However, it outputs to stderr "tar: Removing leading `/' from member names" everytime it runs. Aside from this it runs fine, however, I need to remove this error message. I would just send all stderr to /dev/null, but I want other errors that might actually matter to be remain.

Therefore, my question is is it possible to remove a specific error message from the output using grep or sed and allow others through?

Upvotes: 0

Views: 781

Answers (2)

kvantour
kvantour

Reputation: 26571

The following two methods will only process stderr and do not

1. Process stderr in a subshell:

$ kubectp cp ... 2> >(grep -v 'unwanted error' - )

2. Use redirection swapping to filter stderr:

$ { kubectp cp ... 2>&1 1>&3 | grep -v 'unwanted error' - 1>&2; } 3>&- 3>&1

This does the following:

  • run command kubectp cp ...
  • redirect the output of stdout into fd3 (1>&3) and redirects stderr into stdout (2>&1)
  • process the new stdout (the actual stderr) with grep and redirect the output back to stderr (1>&2)
  • finally, we redirect the output of fd3 back into stderr (3>&1) and close fd3 (3>&-)

Upvotes: 1

user16541120
user16541120

Reputation:

Thanks @CharlesDuffy, solved it with a slight workaround on your answer since I didn't want to turn off set -e:

kubectp cp .... 2>&1 | grep -v 'unwanted error' || true >&2

Upvotes: 0

Related Questions