shell: How to capture stderr output depending on a flag | Sololearn: Learn to code for FREE!

+7

shell: How to capture stderr output depending on a flag

Someone would be able to help me with the TODO in shell/bash which can be seen at https:// github.com/davorpa/shell-utils/commit/230f71a9b2400acc24a7e92889b17bb8cd8b21a4#diff-6c619df767c9a45741832bd40be5d60ba2b2b2b45741832bd40bed6024ba2b1 Is there some approach to capture the output in a local variable or with pipes and conditionally print it afterwards? I have already tried many ways like with command substitution and pipes, but the original output loses colors... escapes. With file descriptors I still do not clarify very well and I always fail. Thanks for support

9/9/2021 10:06:02 PM

David Ordás

4 Answers

New Answer

+4

Yes, there are some ways to capture the output of a command bro. Most of extern commands output something to stdout (Standard Output). You can capture that output, for example, for example, using `` and the command inside of them. For example: output=`echo "hi to everybody"` echo "$output" Output: Hi to everybody Hope this help you, if you're still facing problems, you can DM me, and I will help you๐Ÿ˜Š๐Ÿ˜€

+1

I've read a lot about theory but not fresh with practice and always failing - normal local ecode; ( my-cmd "arg" ) && ecode=$? || ecode=$? - command substitution. $() or legacy `` local output; output=$(my-cmd "arg") local ecode=$? echo -e "$ecode $output" printf '%s %s\n' "$ecode" "$output" - raw eval / exec eval "[email protected]" exec "$0" "[email protected]" - redirect file descriptors: my-cmd "arg" 2>/dev/null #ignore stderr my-cmd "arg" >> file.txt #append all 2 file - temp fds: ๐Ÿ˜– { var="$( { my-cmd; } 2>&1 1>&3 3>&- )"; } 3>&1; - pipes my-cmd "arg" | tee ... - descriptor context exec (๐Ÿ˜ฒbashismo) local var; my-cmd "arg" 2> >( read var <<<&1 ) three first is the unique I know use more or less fine. With command substitution I see in my terminal that colors send by original command are lost. it's rare because new lines don't. with pipes I lost exit code of my-cmd I misunderstand the others: syntax, advantages/disadvantages too much to learn ๐Ÿ˜ฅ

+1

I will try this... with temporal file-descriptors https://unix.stackexchange.com/questions/474177/how-to-redirect-stderr-in-a-variable-but-keep-stdout-in-the-console

0

Yes, that's correct bro๐Ÿ‘๐Ÿ˜€